Assume that the value of a
is 1
, in which case, a<0
is false, so the if-statement goto out;
is skipped and the program resumes sequential execution. The next statement is obviously:
out:
printf("out");
Note that out:
is just a label, so the printf()
statement is executed. Thus, out
is printed, just because it is the next sequential step in the execution of the program (and not because the if
condition was true).
If the value of a
is, say -1
, in which case a<0
is true, so the if-statement, goto out;
is executed and the control goes to:
out:
printf("out");
Thus in both the cases, out
is printed.
To understand better, consider the following example:
#include <cstdio>
int main(){
int a = -1;
if (a<0)
goto in;
out:
printf("out");
in:
printf("in");
return 0;
}
Here, since the value of a
is -1
, a<0
will be true and so, goto in;
will be executed. This will take the control of execution to the following statement:
in:
printf("in");
Thus, the output of the above code snippet is in
.
Live demo of the above code is here.
P.S.: Using a goto statement breaks the normal flow of the program, and hence using it is considered as a bad practise.