23 February, 2013

Commenting Style In 'C' & 'C++'.

Writing comments for improving the readability of the code is a good programming practice observed by most of the serious & good programmers. In 'C' for writing comments in the code we used /* comment specified here */ syntax. This syntax is also valid in C++ and is very much used for writing multiline comments. However for writing single line comments, C++ prefers its users to use the // single line comment syntax. This is because many a times the multiline comment syntax has proved to be problematic while writing nested comments.

Example :

void swap ()
{
     ...
     ...
    
     if ( a > b )
     /* int temp = a;      /* swap a & b */
        a = b;
        b = temp;
     */

}

In the above code we have two comments. One is the outer block commenting the code for swapping two integers. Another is a single line comment that is nested in the outer block comment.

Here the /* end of the single line nested comment puts a premature end to the comment that is supposed to comment out the outer block. This results is an error since the compiler is unable to find a matching /* for the */ of the outer block comment. Therefore the correct way to avoid this error is to prefer the C++ style of writing single line comments.

Example :

void swap ()
{
     ...
     ...
    
     if ( a > b )
     /* int temp = a;      // swap a & b
        a = b;
        b = temp;
     */

}

Now the above code works fine.

Please Visit The Following Articles Of This Blog Before Proceeding Further.
These Links Will Be Beneficial For You & Will Guide You For Better Understanding Of The 'C' & 'C++' Language.




No comments:

Post a Comment

Subscribe To:

Most Commonly Asked Programs In 'C' & 'C++' Language.