Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C vs C++ sizeof [duplicate]

Tags:

c++

c

sizeof

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?

  • C : https://ideone.com/zj5Qd2
  • C++ : https://ideone.com/ZZ4v6S

Seems C prefers global variables over local ones. Is it right?

like image 947
frogatto Avatar asked Jan 07 '16 19:01

frogatto


People also ask

Does C have sizeof?

sizeof is a unary operator in the programming languages C and C++.

Can you print a sizeof in 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.

What is sizeof () in C?

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.

Does sizeof in C return bytes?

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.


1 Answers

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.

like image 185
aschepler Avatar answered Oct 19 '22 04:10

aschepler