Why is this an illegal constant expression?

Viewed 485

I am trying to preserve a variable so I can see its value while debugging optimized code. Why is the following an illegal constant expression?

   void foo(uint_32 x)
   {
       static uint_32 y = x;
       ...
   }
4 Answers

"Why is the following an illegal constant expression?"

Because static variables have to be initialized with a value known at compile-time, while x is only determined at run-time.


Note that this use of static is meant for to keeping the variable with its stored value between different calls to foo() alive (existing in memory) - Means the object won´t get destroyed/ deallocated after one single execution of the function, as it is the case with function-local variables of the storage class automatic.

It wouldn´t make sense to create and initialize a static variable at each function call new.

For your purpose you probably want this:

void foo(uint_32 x)
{
    static uint_32 y;
    y = x;
    ...
}

What you tried to do is an initialisation. What is done above is an assignment.


Maybe for your purpose this would be even more interesting:

static uint_32 y;
void foo(uint_32 x)
{
    y = x;
    ...
}

Now the variable y can easily be accessed by the debugger once the foo function is finished.

A variable declared with the static storage specifier have to be initialized with a constant value.

For example:

#define x 5
void foo()
{
    static int y = x;
}

OR

void foo()
{
    static int y = 5;
}

Another way to answer your question is to remind that you are using C, not C++. The same expression is fully valid in C++ where the initial value for a static variable may not be a constant.

Related