Search code examples
cprintfgoto

Some questions about "goto" in C language


I have some question about goto.Here is my code:

int main(){ 
    int a = 1;
    if (a<0)
        goto out;
    out:
    printf("out");
    return 1;
}

The problem is, whatever the value a is (eg:a=-1 or a=0), the out could printed.
Could anyone tell me the reason, thank you very much.


Solution

  • Regardless if the 'if' statement is entered or not, the next statement will be the printf statement.

    If it skips the 'if statement', printf comes up next, if the 'if statement' is entered, then it goto's the printf. Either way the statement will display.

    The 'out' is kind of like an index that the assembly keeps track of. If the goto 'out' weren't there, the printf would still be there, just without the memory location that the compiler keeps track of.