Hairi Hairi - 2 months ago 6
C Question

Label called outside the loop isn't accessible from outside the loop?

This is the code I was debugging, when I found this(I find interesting).

int function(void) {
static int i, state = 0;
switch (state) {
case 0: goto LABEL0;
case 1: goto LABEL1;
}
LABEL0: /* start of function */
for (i = 0; i < 10; i++) {
state = 1; /* so we will come back to LABEL1 */
return i;
LABEL1:; /* resume control straight after the return */
}
}


So what I observed is that this statement -
goto LABEL1;
never moves the PC directly to the code after the label WHEN THE LABEL IS INSIDE A LOOP. So far so good. Things went really messy when I changed the code to this and debugged again:

int function(void) {
static int i, state = 0;
switch (state) {
case 0: goto LABEL0;
case 1: goto LABEL1;
}
for(;;){
i++;
LABEL0: /* start of function */
for (i = 0; i < 10; i++) {
state = 1; /* so we will come back to LABEL1 */
return i;
LABEL1:; /* resume control straight after the return */
}
}
}


I deliberately nested
LABEL0
into loop so I can confirm the results observed. Though the observations didn't confirm the expected result. This time the
goto
statement sent the program directly to the code after the label it refers to (
LABEL0:)
, despite the label was nested into the dummy
for(;;)
loop.

I really hope you get the scenario. Can anyone explain the behavior(I can't find consistency in)?

Answer

The debugger does often not show the PC very accurately, because a single source line consists of multiple opcodes, and sometimes of no opcodes at all, so it can't always map the PC to the correct source line.

Put a dummy statement after LABEL1 in the first example to see if the PC is set there.