0

In C it is an error

int x=5;
static int y=x; //error

In C++ it is valid why?

int x=5;
static int y=x; //valid
RAJAN_PARMAR
  • 139
  • 2
  • 9
  • Well, according to Clang, *error: initializer element is not a compile-time constant*. I'd wager C requires the initializer to be a compile-time constant. – chris Mar 16 '15 at 18:51
  • 1
    Because C++ can do a _lot_ of things that C can't, and C can do a few things that C++ can't. They're different languages. – Mooing Duck Mar 16 '15 at 18:55

1 Answers1

5

Because C and C++ are different languages.

C++ has a dynamic initialisation stage when the program starts, in which static variables can be initialised using either non-trivial constructors or non-constant initialisers. C doesn't, and requires static variables to be initialised with constant expressions.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
  • why C didn't include such feature . I mean what changes they have done in C to achieve this feature . Because in C and C++ both , static variables are loading time entity . Isn't it? – RAJAN_PARMAR Mar 16 '15 at 19:07
  • Both C and C++ have a *static initialisation* stage - what you might call "loading time". C++ added a *dynamic initialisation* stage after that; C didn't. It has benefits (more convenient initialisation) and problems (the initialisation order fiasco). In C++, it's pretty much needed, since otherwise you couldn't use non-trivial class types for static variables at all; so that benefit was deemed to outweigh the problems. In C, there's no particularly compelling reason to allow that rather than writing code in a function to set the initial value. – Mike Seymour Mar 16 '15 at 19:12