Assume that size of an integer is $32$ bit. What is the output of following ANSI C program?
#include<stdio.h> struct st { int x; static int y; }; int main() { printf(%d",sizeof(struct st)); return 0; }
In C we get compilation error. In C++, we get 4 as output as static members don't occupy space if no object is created.
https://stackoverflow.com/questions/4842056/do-static-members-of-a-class-occupy-memory-if-no-object-of-that-class-is-created#:~:text=No.,size%20even%20by%201%20bit!
printf(%d",sizeof(struct st));
Isn’t this a compiler error?
Static variable isn't allowed in struct because C requires the whole structure elements to be placed "together".
So C is correct.
Ref: https://stackoverflow.com/questions/11858678/are-members-of-a-structure-allowed-to-be-static
@smsubham I am not able to understand why static can't be declared inside a struct. Can you please explain? I am not able to understand from the explanations given in the link. I would be a great help . Thanks
struct st { int x; static int y; };
“y” has to be stored into the “data section” and x has to be stored in “stack frame/ heap ”.
Since C Language requires the entire structure elements to be placed together (i.e.) memory allocation for structure members should be contiguous. Here we can see “x” and “y” are not stored contiguously hence we get a compiler error.
In the below code, we are not getting any error, because “x” and “y” both are stored into “data section” in contiguous memory
NOTE: What about struct in C++, Why it is not showing an error in case of C++?
In C++, struct and class are exactly the same things, except for that struct defaults to public visibility and class defaults to private visibility
Refrences:
64.3k questions
77.9k answers
244k comments
80.0k users