Monday, February 27, 2012

c++ style comments

The good old C comment syntax works in C++ too, but the newfangled C++ comment-to-end-of-line syntax has some distinct advantages. For example, consider this
    if ( a > b ) {
      // int temp = a;    // swap a and b
      // a = b;
      // b = temp;
Here you have a code block that has been commented out for some reason or other, but in a stunning display of software engineering, the programmer who originally wrote the code actually included a comment to indicate what was going on. When the C++ comment form was used to comment out the block, the embedded comment was of no concern, but there could have been a serious problem had everybody chosen to use C-style comments: 
    if ( a > b ) {
      /*  int temp = a;  /* swap a and b */
          a = b;
          b = temp;
Notice how the embedded comment inadvertently puts a premature end to the comment that is supposed to comment out the code block. 
C-style comments still have their place. For example, they're invaluable in header files that are processed by both C and C++ compilers. Still, if you can use C++-style comments, you are often better off doing so. 
It's worth pointing out that retrograde preprocessors that were written only for C don't know how to cope with C++-style comments, so things like the following sometimes don't work as expected: ¤
    #define LIGHT_SPEED   3e8    // m/sec (in a vacuum)
Given a preprocessor unfamiliar with C++, the comment at the end of the line becomes part of the macro! Of course,  you shouldn't be using the preprocessor to define constants anyway. 

No comments:

Post a Comment