I have written a small printf statement which is working different in C and C++:
int i;
printf ("%d %d %d %d %d \n", sizeof(i), sizeof('A'), sizeof(sizeof('A')), sizeof(float), sizeof(3.14));
The output for the above program in c using gcc compiler is 4 4 8 4 8
The output for the above program in c++ using g++ compiler is 4 1 8 4 8
I expected 4 1 4 4 8 in c. But the result is not so.
The third parameter in the printf sizeof(sizeof('A')) is giving 8
Can anyone give me the reasoning for this
It is a compile-time unary operator and used to compute the size of its operand. It returns the size of a variable. It can be applied to any data type, float type, pointer type variables. When sizeof() is used with the data types, it simply returns the amount of memory allocated to that data type.
When applied to arrays, sizeof returns the size of the array in bytes. For example, sizeof(int[10]) returns 40 on a machine where sizeof(int) is 4. Since sizeof(char) is 1, it will equal the amount of characters in a string literal.
So, the sizeof(int) simply implies the value of size of an integer. Whether it is a 32-bit Machine or 64-bit machine, sizeof(int) will always return a value 4 as the size of an integer.
The sizeof operator is used to get the size of types or variable in bytes. Returns an unsigned integer type of at least 16 bit.
It's nothing to do with the sizeof
operator in particular; rather, the size of character literals in C is different than C++, because character literals in C are of type int
, whereas in C++ they are of type char
.
See Why are C character literals ints instead of chars? for more information.
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