Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If I define an array in if statement then does memory get allocated?

Tags:

arrays

c

memory

If I define an array in if statement then does memory gets allocated during compile time eg.

if(1)
{
    int a[1000];
} 
else
{
    float b[1000];
}

Then a memory of 2 * 1000 for ints + 4 * 1000 for floats get allocated?

like image 369
user2738599 Avatar asked Sep 02 '13 04:09

user2738599


2 Answers

It is reserved on the stack at run-time (assuming a non-trivial condition - in your case, the compiler would just exclude the else part). That means it only exists inside the scope block (between the {}).

like image 94
paddy Avatar answered Oct 17 '22 02:10

paddy


In your example, only the memory for the ints gets allocated on the stack (1000 * sizeof(int)).

As you can guess, this is happening at run time. The generated code has instructions to allocate the space on the stack when the corresponding block of code is entered.

Keep in mind that this is happening because of the semantics of the language. The block structure introduces a new scope, and any automatic variables allocated in that scope have a lifetime that lasts as long as the scope does. In C, this is implemented by allocating it on the stack, which collapses as the scope disappears.

Just to drive home the point, note that the allocation would be different had the variables been of different nature.

if(1)
 {
  static int a[1000];
 } 
else
 {
  static float b[1000];
 }

In this case, space is allocated for both the ints and the floats. The lifetime of these variables is the program. But the visibility is within the block scope they are allocated in.

like image 33
Ziffusion Avatar answered Oct 17 '22 00:10

Ziffusion