Search code examples
cactivation-record

A block scoped variable and the activation record


I understand that local variables (along with other stuff) are placed in the activation record. And the activation record must exist before the function begins executing. Consider the function below:

void f(void)
{
    int i;
    scanf("%d", &i);
    if (i > 10) {
        int j = 22;
        // do some operations on j here.
    }
    // more code below...
}

Looking at this function, it seems that the the variable j might or might not exist depending entirely on the user's input at runtime. In this case,

  1. Will the variable j be placed in the activation record?
  2. Is this implementation defined (in other words, will some compiler generate code equivalent to j being declared outside and above the if` block)?
  3. Or, will j be simply allocated on the stack segment during execution if need be? But, in that case how will j go out of scope after the if block?

I could not find much information regarding this in the C11 spec. Thanks in advance.


Solution

  • Activation record is also called stack frame, if I am not mistaken. I believe that these are the answers:

    Q1. Will the variable j be placed in the activation record?

    A1:Yes, unless optimized out by compiler.

    Q2. Is this implementation defined (in other words, will some compiler generate code equivalent to j being declared outside and above the if` block)?

    A2:It is implementation defined. Depends on the compiler and settings of the compiler, but in most cases, j will be in activation record.

    Q3. Or, will j be simply allocated on the stack segment during execution if need be? But, in that case how will j go out of scope after the if block?

    A3: No, allocation in C is typically not dependent on the content of the local variable.