Reputation: 9996
Today, i was a little bit surprised about the behavior of c structure vs c++ structure.
fun.cpp: http://ideone.com/5VLPC
struct nod
{
static int i;
};
int main()
{
return 0;
}
The above program works perfectly.
BUT,
When the same program is run in C environment, it is giving the error:
prog.c:3: error: expected specifier-qualifier-list before ‘static’
see here: http://ideone.com/2JRlF
Why it is so?
Upvotes: 0
Views: 186
Reputation: 279315
Each C++ class has its class namespace, so you can refer to that static data member as nod::i
from outside the class namespace, and just plain i
inside it. C has no namespace scopes, and there's no code "in" C structs, so there's no way to hide globals in namespaces or to refer to them by their unqualified name in their own scope. So there was no motivation in C to have the thing that in C++ is called static data members.
Just do int nod_i;
.
Upvotes: 4
Reputation: 20738
Because in C++, structs are just classes with default visibility of public
. So in C, the struct is only a aggregation of data, which does not know anything about the fact that it could be percieved as standalone type.
See also What are the differences between struct and class in C++
Upvotes: 7
Reputation: 258618
static
in C only has the meaning of internal linkeage. Don't think of a C-struct
as you would of a struct
or a class
in C++. It's just an aggregator, not the OOP construct.
As C doesn't have classes, this use of static
doesn't make sense.
Upvotes: 3