Online Test Banks
Score higher
See Online Test Banks
Learning anything is easy
Browse Online Courses
Mobile Apps
Learning on the go
Explore Mobile Apps
Dummies Store
Shop for books and more
Start Shopping

Watching Out for Nested Comments in C

Because C's comments start and end with specific characters, you cannot put one comment inside another. This is known as nesting. Nested comments can cause errors in your code, so while you're programming, keep track of where comments start and end.

For example, imagine you start with this code:

#include <stdio.h>
int main()
    printf("The First Soloist\n\n");  /* Extra blank line */
    printf("Vocalist Mary McDiva\n");
/*  printf("Song, "Under the Sea."\n"); */

The following figure shows how the compiler sees this source code. Note how the commented parts of the code are grayed out? That's the part the compiler ignores as a comment.


Line 7 was commented out because it caused an error (all those quotation marks threw off the compiler). Now suppose that the programmer goes back and adds a reason for the
comment — and pay special attention to what is done:

#include <stdio.h>
int main()
    printf("The First Soloist\n\n");  /* Extra blank line */
    printf("Vocalist Mary McDiva\n");
/* Can't get this following line to compile:
 * /*  printf("Song, "Under the Sea."\n"); */
 * displays some kind of error

Despite the fancy, lined-up asterisks at the start of each line, the block of four lines is not a comment. The programmer probably intended for that entire section to be a comment and to be ignored by the compiler, but the following figure illustrates what really happens:


The first time the compiler encounters the */ characters, it assumes that the commented section is over, so it continues to compile the text that's left. That's where the errors happen.

The moral of the story is to remember that the /* starts a comment and */ ends the comment. If you stick one comment inside another, something bad happens.

By the way, this situation is easy to see if your editor color-codes your text. For example, in the VIM editor, comments appear blue on the screen. If you forget to end a comment or accidentally nest a comment, you can see the blue text spill over into areas where you don't want it. That way, those types of errors are easy to spot and fix.

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus

Inside Sweepstakes

Win $500. Easy.