clanguage-lawyerlifetimestorage-durationc17

Is jumping to the beginning of the block equivalent to "entering the block"?


Consider the below example code:

int jump_count = 0;

int main()
{
entry:
    int obj = jump_count;
    printf("%d\n", obj);
    jump_count++;

    if(jump_count < 2) goto entry;

    return 0;
}

Is my jumping to the beginning of the block (as mentioned in the above code) equivalent to "entering the block"?


Solution

  • The definition of a "block" in C is pretty much this (ISO 9899:2024 6.8.3):

    6.8.3 Compound statement
    Syntax
    compound-statement:
    { block-item-listopt }

    block-item-list:
    block-item
    block-item-list block-item

    block-item:
    declaration
    unlabeled-statement
    label

    Semantics
    A compound statement that is a function body together with the parameter type list and the optional attribute specifier sequence between them forms the block associated with the function definition in which it appears.

    If we decipher the formal syntax we can for example conclude that a label is one of the items that may appear inside a block. The { and } is the key, showing where the block begins and where it ends. A goto from within the block to a label within the same block never causes the program counter to enter or leave the block.

    "Entering the block" isn't really a formal term but the standard mentions it here and there. You can enter a block either by coming from the code just before it (which may be a function definition and the function was just called, or a loop condition etc) or by a goto from an outer block. goto may only jump within the enclosing function however. And naturally there's various dangers with wildly jumping into a block with goto, for example if there is a VLA array there and we jump past the variable definition of that VLA.

    One example of "entering the block" can be found in the definition of loops, 6.8.6:

    An iteration statement causes a secondary block called the loop body to be executed repeatedly until the controlling expression compares equal to 0. The repetition occurs regardless of whether the loop body is entered from the iteration statement or by a jump.