Rasmi Ranjan Nayak
Rasmi Ranjan Nayak

Reputation: 11998

Why I can not initialize and int value to a static variable

I am getting ERROR when I am running this program at the line

static int b = a; //error : initializer element is not constant

Can not understand why?

 #include <stdio.h>
   // #include <setjmp.h>
    int main()
    {
    int a = 5;
    static int b = a;

    return 0;
    }

Upvotes: 2

Views: 354

Answers (4)

Thorsen
Thorsen

Reputation: 413

Following from Als's answer ...

// This is really crappy code but demonstrates the problem another way ....
#include <stdio.h>
int main(int argc, char *argv[])
{
static int b = argc ; // how can the compiler know 
                      // what to assign at compile time?

return 0;
}

Upvotes: 0

Jay
Jay

Reputation: 24915

Apart from the other reasons stated in other answers here, please see the below statement in the Standard.

The C Standard says this in Point-4 (Section 6.7.8 Initialization):

All the expressions in an initializer for an object that has static storage duration
shall be constant expressions or string literals.

Additionally, as to what is a constant expression, it says in Section 6.6 Constant Expressions as below:

A constant expression can be evaluated during translation rather than runtime, and
accordingly may be used in any place that a constant may be.

Upvotes: 3

CB Bailey
CB Bailey

Reputation: 793279

In C (unlike C++), the initializer for any object with static storage duration - including function statics - must be constant expressions. In your example a is not a constant expression so the initialization is not valid.

C99 6.7.8 / 4:

All the expressions in an initializer for an object that has static storage duration shall be constant expressions or string literals.

Upvotes: 2

mity
mity

Reputation: 2349

Static variable is always global in the sense it is not on any thread's stack, and it is not important if its declaration is inside a function or not.

So the initialization of the global variable b is performed during program start-up, before any function (including main) gets called, i.e. no a exists at that time, because a is local variable which gets its memory place on stack after the function (here main) is called.

Hence you really cannot expect the compiler to accept it.

Upvotes: 1

Related Questions