Wednesday, January 4, 2012

Can a comment appear in a C statement?

That depends. The C compiler treats comments like a single white space character. Therefore, comments can appear in a C statement only where a white space character is allowed. This means that comments may be placed between tokens but not within a token. (Note: a string literal is a token.)

Examples of correct comments:

printf /*This comment is legal */("Welcome to C!");
printf ( /*This comment is also legal*/"Welcome to C!");

Examples of incorrect comments:

pr /* This comment is illegal because it splits a C function
name (i.e., a token) */ intf("Welcome to C!");

printf("This is not a comment and /*will be displayed*/ ");

The text contained in the /* and */ is not a comment because it becomes part of the string literal and will be displayed. For this incorrect comment, the compiler will not indicate an error, it will simply print the phrase:

This is not a comment and /*will be displayed*/

on the screen. For the other comments, the compiler will indicate an error when you try to compile the program.

No comments:

Post a Comment