cfunctionif-statementstacklocal-variables

Defining a variable inside an if condition and program doesn't enter


In functions in C, I understand that the stack is normally used to store paramaters passed to a function, and for the local variables for the function. I know that this is compiler and platform-dependent as registers can also be used, but let's say that the stack is just used in this case.

Is space normally reserved on the stack for local variables regardless of where they get defined inside that function?

For example if we have an if condition in the function, and when it's true, variables are defined inside the if block. Will the push() operations only be called when entering the block, and pop() on leaving the block?

Or is it the case that space gets reserved on the stack for these variables regardless of whether the if condition is true or not?


Solution

  • Well, this is completely implementation-defined. Let's ignore anything about optimization and explain this question according to standard C.

    The first thing is that C standard specifies nothing about memory layout. So the implementations(i.e. somehow compilers) can choose any way to allocate memory space for objects(i.e. somehow variables) as long as they obey the lifetime constraint.

    The lifetime of an object is the portion of program execution during which storage is guaranteed to be reserved for it.

    Objects defined in a if statement(without static and thread_local specifier) have the "automatic storage duration", whose lifetime starts from entering of the block and ends at leaving the block.

    Therefore, the answer for "whether the memory space for an automatic storage duration object is allocated ahead of time or just in time" is completely depends on implementation.

    In practice, "local variables" are often allocate ahead of time(even in ancient x86 ISA, such as 8086). But for VLA, they can only be allocated just in time. If you really want to know the behavior under a specific implementation, just refer to its documentation(e.g. GCC's user manual and internal document).