0

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?

Green goblin
  • 9,898
  • 13
  • 71
  • 100

3 Answers3

7

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++

Community
  • 1
  • 1
Jonas Schäfer
  • 20,140
  • 5
  • 55
  • 69
4

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;.

Steve Jessop
  • 273,490
  • 39
  • 460
  • 699
3

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.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625