in Programming retagged by
993 views
3 votes
3 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;
}
  1. $4$
  2. $8$
  3. Compiler Error
  4. Runtime Error
in Programming retagged by
993 views

2 Comments

edited by

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!

0
0
printf(%d",sizeof(struct st));

Isn’t this a compiler error? 

0
0

1 Answer

1 vote
1 vote

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

2 Comments

@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
0
reshown by

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: 

 

1
1
Answer:

Related questions