Home > Net >  what is empty function size?
what is empty function size?

Time:01-08

integer is 4 byte

double is 8 byte

What is the size of an empty function?

void test(){} //-> size????
void test1(){ int a, int b, double c } //-> size????
void test2(){ test() }  -> size??????

When I run the program, the result is the same

void test(){} 
void test1() {int a} 

void main()
{
     cout<<sizeof(&test) <<endl;
     cout<<sizeof(&test1) <<endl;
}

please solve my questions

CodePudding user response:

ISO C does not have a notion of the size of a function.

How the compiler creates the machine-level instructions for the individual functions and merges them into an entire program is not specified by the ISO standard. Every individual platform can do this its own way. Therefore, it would not make sense for the ISO standard to attempt to define what the size of a function is.

As a consequence, you cannot use the sizeof operator to determine the size of a function.

When you write the expression &test, you get a pointer that points to the function test. On 32-bit platforms, pointers are usually 32 bits (i.e. 4 bytes), and on 64-bit platforms, they are usually 64 bits (i.e. 8 bytes).

That is why the expressions

sizeof(&test)

and

sizeof(&test1)

will both evaluate to either 4 or 8, depending on your platform.

Depending on how code is generated on your platform, you may be able to find a meaningful definition of the size of a function, and find the size of a function in a platform-specific manner. However, most platforms perform compiler optimizations which allow functions to be, for example, inlined, so that they may not even exist as a separate entity. In such a case, it is probably hard to find a meaningful definition of the size of a function.

CodePudding user response:

There is no concept of size of a function in C . When you do sizeof(&test), you just get the size of a function pointer, which can only dependent on the function type and it is likely that all function pointer types will have the same size.

If you want to know the size of a function in terms of the number of instructions in it or the number of bytes these instructions occupy in memory, you cannot use core C or its standard library to achieve that directly. Instead you can look at the compiled object files with external tools, see e.g. this question, or potentially with platform-specific libraries or compiler intrinsics/extensions.

  •  Tags:  
  • Related