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

梦想的初衷 提交于 2019-12-07 13:09:18

问题


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...
     };
 }

回答1:


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");
}



回答2:


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...
         };
}



回答3:


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.




回答4:


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



来源:https://stackoverflow.com/questions/1334069/are-const-arrays-declared-within-a-function-stored-on-the-stack

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!