Dynite
Dynite

Reputation: 2383

Are const arrays declared within a function stored on the stack?

if this was declared within a function, would it be declared on the stack? (it being const is what makes me wonder)

void someFunction()
{

     const unsigned int actions[8] = 
     {       e1,
             e2,
             etc...
     };
 }

Upvotes: 3

Views: 470

Answers (4)

xtofl
xtofl

Reputation: 41509

Yes, they're on the stack. You can see this by looking at this code snippet: it will have to print the destruction message 5 times.

struct A { ~A(){ printf( "A destructed\n" ); } };

int main() {
    {
      const A anarray  [5] = {A()} ;
    }
    printf( "inner scope closed\n");
}

Upvotes: 5

StackedCrooked
StackedCrooked

Reputation: 35485

Yes, non-static variables are always created on the stack.

Upvotes: 0

Tadeusz Kopec for Ukraine
Tadeusz Kopec for Ukraine

Reputation: 12413

If you don't want your array to be created on stack, declare it as static. Being const may allow the compiler to optimize whole array away. But if it will be created, it will be on stack AFAIK.

Upvotes: 2

Kim Gräsman
Kim Gräsman

Reputation: 7586

As I understand it: yes. I've been told that you need to qualify constants with static to put them in the data segment, e.g.

void someFunction()
{
     static const unsigned int actions[8] = 
         {
             e1,
             e2,
             etc...
         };
}

Upvotes: 4

Related Questions