Search code examples
cstackgoto

State of the stack after goto


In the following C code, f calls g, and g calls h. Notice the goto in h, however: it will jump back to f if a satisfies a certain condition.

void h(int a)
{
    if (a > 10)
        goto out;
}

void g(int a, int b)
{
    h(a);
}

void f(int a, int b)
{
    g(a, b);
    return;
out:
    printf("b: %d\n", b);
}

My question is: how will the stack be if the goto is triggered? Will g and h be unstacked? And will f still print the right value of b? (or will it print it right only in some cases when I am lucky?)

(Please, I don't want to discuss if this is a good practice, or if this should be used at all. Also, consider that the actual code is complicated enough so that the compiler won't be smart enough to, e.g., optimize g out)

[I can give details on why I am doing this, if it matters -- I don't think it does]


Solution

  • This will result in undefined behavior in standard C.

    From 6.8.6.1/1 of the C Language Standard:

    The identifier in a goto statement shall name a label located somewhere in the enclosing function. A goto statement shall not jump from outside the scope of an identifier having a variably modified type to inside the scope of that identifier.