Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this an illegal constant expression?

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;
       ...
   }
like image 643
Pistanic Avatar asked Dec 23 '22 18:12

Pistanic


2 Answers

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.

like image 89
Jabberwocky Avatar answered Dec 30 '22 06:12

Jabberwocky


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

like image 41
RobertS supports Monica Cellio Avatar answered Dec 30 '22 06:12

RobertS supports Monica Cellio