Sunday 20 November 2011

What is the difference between continue and break? in C programming

What is the difference between continue and break?

A continue statement is used to return to the beginning of a loop. The break statement is used to exit from a loop. For example, here is a typical continue statement:

while (!feof(infile)
{
fread(inbuffer, 80, 1, infile); /* read in a line from input file */
if (!strncmpi(inbuffer, “REM”, 3)) /* check if it is
a comment line */
continue; /* it’s a comment, so jump back to the while() */
else
parse_line(); /* not a comment--parse this line */
}
In this example, a file is being read and parsed. The letters “REM” (short for “remark”) are used to denote
a comment line in the file that is being processed. Because a comment line means nothing to the program,
it is skipped. As each line is read in from the input file, the first three letters of the line are compared with
the letters “REM.” If there is a match, the input line contains a comment, and the continue statement is used
to jump back to the while statement to continue reading in lines from the input file. Otherwise, the line must
contain a valid statement, so the parse_line() function is called.
A break statement, on the other hand, is used to exit a loop. Here is an example of a break statement:
while (!feof(infile)
{
fread(inbuffer, 80, 1, infile); /* read in a line from input file */
if (!strncmpi(inbuffer, “REM”, 3)) /* check if it is
a comment line */
continue; /* it’s a comment, so jump back to the while() */
else
{
if (parse_line() == FATAL_ERROR) /* attempt to parse
this line */
break; /* fatal error occurred, so exit the loop */
}
}

This example builds on the example presented for the continue statement. Notice that in this example, the return value of the parse_line() function is checked. If the parse_line() function returns the value FATAL_ERROR, the while loop is immediately exited by use of the break statement. The break statement causes the loop to be exited, and control is passed to the first statement immediately following the loop.

Cross Reference:

XIX.14: What is the difference between a null loop and an infinite loop?

No comments:

Post a Comment