Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't we declare a static variable within a structure in the C programming language?

Tags:

c

Why can't we declare a static variable within a structure in the C programming language?

like image 664
Jagan Avatar asked Sep 19 '10 07:09

Jagan


People also ask

Why we Cannot declare static variable inside a static method?

Static variables in methods i.e. you cannot use a local variable outside the current method which contradicts with the definition of class/static variable. Therefore, declaring a static variable inside a method makes no sense, if you still try to do so, a compile time error will be generated.

Can we declare static in structure?

You can use Static only on local variables. This means the declaration context for a Static variable must be a procedure or a block in a procedure, and it cannot be a source file, namespace, class, structure, or module. You cannot use Static inside a structure procedure.

Can we declare static variable as global in C?

Static keywords can be used to declare a variable inside a function as well as to declare a global variable.

Can we declare variable in structure?

The structure members can have any variable types except type void , an incomplete type, or a function type. A member cannot be declared to have the type of the structure in which it appears.


3 Answers

In C++, a struct is basically a class with all members public, so a static variable makes good sense there.

In C, a struct is a contiguous chunk of memory with fields. A static variable can not be created without changing that (as to implement a static you need to refer to a single memory location from all structs of that type), and that would be a big difference in complexity without much benefit.

like image 45
MaxVT Avatar answered Mar 05 '23 12:03

MaxVT


Because C is not C++.

Because the C standard does not permit it.

Because it has no meaningful interpretation in C.

like image 38
Jonathan Leffler Avatar answered Mar 05 '23 13:03

Jonathan Leffler


Static variables should not be declared inside structure.The reason is C compiler requires the entire structure elements to be placed together (i.e.) memory allocation for structure members should be contiguous. It is possible to declare structure inside the function (stack segment) or allocate memory dynamically(heap segment) or it can be even global (BSS or data segment). Whatever might be the case, all structure members should reside in the same memory segment because the value for the structure element is fetched by counting the offset of the element from the beginning address of the structure. Separating out one member alone to data segment defeats the purpose of static variable.

It is possible to have an entire structure as static.

reference : https://en.wikipedia.org/wiki/Static_(keyword)

like image 129
MK Tharma Avatar answered Mar 05 '23 12:03

MK Tharma