Why does the following code give:
#include<stdio.h>
int voo()
{
printf ("Some Code");
return 0;
}
int main() {
printf ("%zu", sizeof voo);
return 0;
}
The following output:
1
When sizeof() is used with the data types, it simply returns the amount of memory allocated to that data type. The output can be different on different machines like a 32-bit system can show different output while a 64-bit system can show different of same data types.
The sizeof operator applied to a type name yields the amount of memory that can be used by an object of that type, including any internal or trailing padding. The result is the total number of bytes in the array. For example, in an array with 10 elements, the size is equal to 10 times the size of a single element.
Sizeof is a much used operator in the C or C++. It is a compile time unary operator which can be used to compute the size of its operand. The result of sizeof is of unsigned integral type which is usually denoted by size_t.
The sizeof() is an operator that evaluates the size of data type, constants, variable. It is a compile-time operator as it returns the size of any variable or a constant at the compilation time. The size, which is calculated by the sizeof() operator, is the amount of RAM occupied in the computer.
The C language does not define sizeof
for functions. The expression sizeof voo
violates a constraint, and requires a diagnostic from any conforming C compiler.
gcc implements pointer arithmetic on function pointers as an extension. To support this, gcc arbitrarily assumes that the size of a function is 1, so that adding, say, 42 to the address of a function will give you an address 42 bytes beyond the function's address.
They did the same thing for void, so sizeof (void)
yields 1, and pointer arithmetic on void*
is permitted.
Both features are best avoided if you want to write portable code. Use -ansi -pedantic
or -std=c99 -pedantic
to get warnings for this kind of thing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With