The meaning of continue in C
Posted by peeterjoot on June 16, 2010
I found myself looking at some code and unsure how it would behave. Being a bit tired today I couldn’t remember if continue pops you to the beginning of the loop, or back to the predicate that allows you to break from it. Here’s an example:
int main()
{
volatile int rc = 0 ;
volatile int x = 0 ;
do {
rc = 1 ;
if ( 1 == x )
{
rc = 0 ;
continue ;
}
} while ( rc == 1 ) ;
return 0 ;
}
And if you say, “What you’ve been programming for 12 years and don’t know?” Well it looks that way. I chose to walk through this code in the debugger to see how it worked:
(gdb) b main
Breakpoint 1 at 0x40055c: file t.C, line 3.
(gdb) run
Starting program: /vbs/engn/.t/a.out
Breakpoint 1, main () at t.C:3
3 volatile int rc = 0 ;
(gdb) n
4 volatile int x = 0 ;
(gdb) n
7 rc = 1 ;
(gdb) n
9 if ( 1 == x )
(gdb) n
6 do {
(gdb) n
7 rc = 1 ;
(gdb) n
9 if ( 1 == x )
(gdb) p x=1
$1 = 1
(gdb) n
11 rc = 0 ;
(gdb) n
6 do {
(gdb) n
17 return 0 ;
(gdb) n
18 }
(gdb) q
Once the variable x is modified, sure enough we break from the loop (note the sneaky way you have to modify variables in gdb, using the print statement to implicitly assign). There’s no chance to go back to the beginning and reset rc = 1 to keep going.
The conclusion: continue means goto the loop exit predicate statement, not continue to the beginning of the loop to retry. In the code in question a goto will actually be clearer, since what was desired was a retry, not a retry-if.