4 votes 4 votes 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; } $4$ $8$ Compiler Error Runtime Error Programming in C nielit2017july-scientistb-it programming-in-c output + – admin asked Mar 30, 2020 retagged Oct 29, 2020 by Krithiga2101 admin 2.0k views answer comment Share Follow See all 2 Comments See all 2 2 Comments reply Ollie commented Jun 10, 2020 i edited by Ollie Jun 10, 2020 reply Follow Share 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! 1 votes 1 votes neel19 commented May 11, 2022 reply Follow Share printf(%d",sizeof(struct st)); Isn’t this a compiler error? 0 votes 0 votes Please log in or register to add a comment.
1 votes 1 votes 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 answered Mar 30, 2020 smsubham comment Share Follow See all 2 Comments See all 2 2 Comments reply Pratyush Priyam Kuan commented Jun 6, 2020 reply Follow Share @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 0 votes 0 votes nocturnal123 commented Aug 23, 2020 i reshown by nocturnal123 Aug 23, 2020 reply Follow Share 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: https://stackoverflow.com/questions/3744899/why-cant-we-declare-a-static-variable-within-a-structure-in-the-c-programming-l https://www.geeksforgeeks.org/difference-c-structures-c-structures/ 2 votes 2 votes Please log in or register to add a comment.