Comments

From Tux
Jump to: navigation, search

Comments

Syntactically, comments in C++ can be accomplished in two ways:

  • Single line comments are prefaced by // and end at the end of the line they are placed on
  • Multi-line comments are placed between /* and */ and can span multiple lines
// This is a single line comment

This is not a comment     // but this is

cout << "Hi!" << endl;    // This is a comment but the cout statement is not a comment

/* This is also technically a single line comment but using the multi-line comment format */

/* Everything
   in
   here
   is a comment */

cout << "Hi!" << endl;    // This is a single line 
cout << "Hi!" << endl;    //  comment format but 
cout << "Hi!" << endl;    //  spanning over 
cout << "Hi!" << endl;    //  multiple lines.

cout << "Hi 1" << endl;    /* This multi-line comment actually
cout << "Hi 2" << endl;        ends up removing the last three
cout << "Hi 3" << endl;        cout statements and therefore 
cout << "Hi 4" << endl;        only "Hi 1" will be displayed. */

It is common to use comments:

  • At the top of your source code to provide your name, the class and section, and a description of what the program does
  • Throughout the code when necessary to explain functions and particularly complicated algorithms
  • When trying to leave out code because it's partially written or buggy -- commonly called commenting out the code

Links