Jagan
Jagan

Reputation: 4897

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

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

Upvotes: 10

Views: 12425

Answers (4)

MK Tharma
MK Tharma

Reputation: 31

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)

Upvotes: 3

Nitesh
Nitesh

Reputation: 315

Because in c we can't access static variable with stucture name. In c++ we can access static member variable with class name,like below.

ClassName::staticVariableName

'C' stucture don't provide such facility.

Upvotes: 1

MaxVT
MaxVT

Reputation: 13234

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.

Upvotes: 16

Jonathan Leffler
Jonathan Leffler

Reputation: 754420

Because C is not C++.

Because the C standard does not permit it.

Because it has no meaningful interpretation in C.

Upvotes: 5

Related Questions