I just came across this simple code snippet and am wondering why output of this program when it's compiled by a C compiler is 4
and when it's compiled by a C++ one is 8
.
#include <stdio.h> int x; int main(){ struct x {int a; int b;}; printf("%d", sizeof(x)); return 0; }
C++ output is rational (8 = 4 + 4 = sizeof(x.a) + sizeof(x.b)
), but output of C isn't. So, how does sizeof
work in C?
Seems C prefers global variables over local ones. Is it right?
sizeof is a unary operator in the programming languages C and C++.
The sizeof(variable) operator computes the size of a variable. And, to print the result returned by sizeof , we use either %lu or %zu format specifier.
The sizeof() function in C is a built-in function that is used to calculate the size (in bytes)that a data type occupies in the computer's memory. A computer's memory is a collection of byte-addressable chunks.
sizeof always returns size as the number of bytes. But according to wikipedia: In the programming languages C and C++, the unary operator sizeof is used to calculate the size of any datatype, measured in the number of bytes required to represent the type.
In C, a struct definition like struct x { int a; int b; };
does not define a type x
, it defines a type struct x
. So if you remove the int x;
global, you'll find the C version does not compile.
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