Search code examples
clanguage-lawyergoto

Validity of forcing at least one iteration of for loop with goto statement


Disclaimer: I know it is obscure, and I would not program like that. I am aware of the preferred do-while statement, rather than that, the question is more about validity of a specific language construct.


Is goto always supposed to omit conditional expression of the for loop? From what I observed it skips both the first (i.e. initializing) and second expressions. Will this always happen this way or is this behavior purely compiler dependent?

#include <stdio.h>

int main(void)
{
    int m = 5;

    goto BODY;
    for (m = 0; m < 5; m++)
        BODY: puts("Message"); // prints "Message" once

    printf("m = %d\n", m); // prints m = 6

    return 0;
}

Solution

  • Yes, you're jumping over both m = 0 and m < 5, and this is as it should be.

    for (A; B; C)
        D;
    

    is equivalent to

    {
        A;
      loop:
        if (B)
        {
            D;
            C;
            goto loop;
        }
    }
    

    There is no way to transfer control to a point between A and B.

    The semantics of your loop are exactly like this "pure goto" version:

    int m = 5;
    goto BODY;
    m = 0;
    loop:
    if (m < 5) 
    {
      BODY: puts("Message"); // prints "Message" once
       m++;
       goto loop;
    }
    printf("m = %d\n", m); // prints m = 6