Misplaced semicolons can cause subtle bugs:
#include <stdio.h>
main()
{
int count;
for( count = 0; count < 500; count++ ); /* Error! */
{
printf( "count = %d\n", count );
printf( "And the beat goes on...\n" );
}
}
You might expect the program to print the value of count 500 times, but this is all it prints:
count = 500
And the beat goes on...
The culprit is the extra semicolon immediately after the parentheses of the for statement. Its effect is more evident if we reformat the statement:
#include <stdio.h>
main()
{
int count;
for( count = 0; count < 500; count++ )
; /* Null statement */
{
printf( "count = %d\n", count );
printf( "And the beat goes on...\n" );
}
}
Instead of printing the value of count 500 times, the program executes the null statement (;) 500 times. Null statements are perfectly legal in C, so the compiler has no way to tell this is a mistake.
Since the null statement is interpreted as the loop body, the printf statements inside curly braces are interpreted as a statement block and executed once. Statement blocks usually appear as part of a loop, function definition, or decision- making statement, but it's legal to enclose any series of statements in braces.
The program works as intended if you remove the extra semicolon:
#include <stdio.h>
main()
{
int count;
for( count = 0; count < 500; count++ )
{
printf( "count = %d\n", count );
printf( "And the beat goes on...\n" );
}
}
Here's another one. If you know QuickPascal, you might be tempted to put a semicolon after the parentheses of a function definition:
void func( void );
void func( void ); /* Error! No semicolon here. */
{
printf( "C is not Pascal\n" );
}
The function header causes a syntax error. While a function declaration requires a semicolon after its parentheses, a function definition does not. This code corrects the error:
void func( void );
void func( void )
{
printf( "C is not Pascal\n" );
}