LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   C/C++ Comment Style (https://www.linuxquestions.org/questions/programming-9/c-c-comment-style-623323/)

JMJ_coder 02-23-2008 11:47 AM

C/C++ Comment Style
 
Hello,

For all the C/C++ programmers out there:

What is your favorite comment style for your source code (C programmers, ignore all the //'s ;))

Box Comments
Code:

/*---------------------------------------------*/
/*                                            */
/* This is a comment box                      */
/*                                            */
/*---------------------------------------------*/

Inline Comments
Code:

void SomeFunction (int *num1)
{// This is an inline comment to describe this function

  num1 = SomeCode();

}

Single Line Comments
Code:

// This is a single line comment to describe the following function

void SomeFunction (int *num1)
{

  num1 = SomeCode();

}

Code:

/* This is a single line comment to describe the following function */

void SomeFunction (int *num1)
{

  num1 = SomeCode();

}


Vertical Column Comments
Code:

/*
 *
 * This is a vertical column comment
 * 
 * that will describe what this program
 *
 * will do!
 *
 */

Code:

/*
 *  This is a vertical column comment to describe the following function
 */

void SomeFunction (int *num1)
{

  num1 = SomeCode();

}

Some other kind?



Also, how much do you comment your source code? Does every inane thing have a comment (i.e., this is the #include section, this defines functions SomeFunction1() and SomeFunction2())?

H_TeXMeX_H 02-23-2008 01:26 PM

I'm trying to figure this stuff out too. Usually I use C++ style comments for regular comments and the C style comments to comment out large sections of code (including possible C++ comments), which would not be possible if I used C style comments for everything.

Here's a sample program I wrote a couple days ago just for fun, don't expect it to be perfect or a good idea, I'm not an expert C programmer.

Code:

// generate random numbers using /dev/urandom

// includes
#include <stdio.h>
#include <stdlib.h>

// defines
#define NUM_RAND 10

// main
int main(void)
{
  // init vars
  unsigned int seed = 0; // random seed
 
  // ! init vars
  FILE *urandom; // file handle for /dev/urandom
  unsigned int i; // all-purpose counter
 
  urandom = fopen("/dev/urandom", "rb"); // open /dev/urandom as readonly binary
  if (urandom == NULL) // did it open ?
  {
    perror("!!! ERROR: could not open /dev/urandom for reading !!!");
    exit(1); // fail
  }
 
  // read the one seed from urandom
  if (fread(&seed, sizeof(int), 1, urandom) < 1) // did it read ?
  {
    perror("!!! ERROR: failed to read from /dev/urandom !!!");
    exit(1); // fail
  }
 
  // we are now finished reading from /dev/urandom, close it
  fclose(urandom);
 
  // print the seed just to make sure
  printf("The seed obtained from /dev/urandom is %u\n", seed);
 
  // seed rand with seed
  srand(seed);
 
  // generate some random numbers
  for (i = 1; i <= NUM_RAND; i++)
  {
    printf("Random number #%d, is %d\n", i, rand());
  }
 
  // success
  return 0;
}

I like to put lots of comments in my code, but not so much as to explain the obvious, still enough to help you make sense of what I'm doing.

And, yes probably for the header it's better to do something fancy like:

Code:

/**********************************************************/
/*                      ______                                  */
/*                      /    /\                          */
/*                    /    /  \                          */
/*                    /    / /\ \                          */
/*                  /    / /  \ \                          */
/*                  /    /  \  \ \                          */
/*                /    / /\ \___\/                          */
/*                /_____/ /  \ \                          */
/*                \    \ \  \ \                          */
/*                \    \ \___\/                          */
/*                  \    \ \                                  */
/*                  \    \ \                                  */
/*                    \_____\/                                  */
/*                                                        */
/*  Name: Bob                                                  */
/*                                                          */
/*  Company: E-corp                                          */
/*                                                          */
/*  Date: 23-Sept-2008                                          */
/*                                                          */
/*  Program: random.c                                          */
/*                                                          */
/*  Description:                                          */
/*  generates random numbers using /dev/urandom                  */
/*                                                          */
/**********************************************************/


osor 02-23-2008 02:54 PM

Quote:

Originally Posted by JMJ_coder (Post 3067349)
C programmers, ignore all the //'s ;)

The //-style comment is now (as of C99) part of C, so C programmers are free to use them too.

Anyway, I comment mostly with single-line comments prior to important functions and prior to or on the same line as statements with non-obvious results. On some projects I place column-style comments prior to a function, describing all inputs and outputs. I don’t use any fancy box styles, although the boxes program allows you to create them in editors like vi. My favorite of their examples is the peek style.

Btw, you completely forgot preprocessor comments. These aren’t really comments at all per se (they’re not supposed tell you anything about the code), but they allow one to “comment out” large sections of code and make it easy to “uncomment” quickly. Another benefit here is you can put them around normal (multi-line) comments without worrying. This is most useful when you have a function which you want to replace or get rid of. For example,
Code:

#if 0
/* Function: int dosomething(int arg1)
 *
 * Purpose: This function does something
 *
 * Inputs: arg1 - what is to be done
 *
 * Returns: The number of somethings done
 */
int dosomething(int arg1)
{
        //something is done here
}
#endif

In this case, you might have originally had a function dosomething(), but it turns out later that you don’t need it anymore (or perhaps you need the name for a new function). If you ever want to use the function again, just replace 0 by 1 and the whole thing will be uncommented.

95se 02-23-2008 03:15 PM

Well, I comment ALL functions (/methods), usually using doxygen (or Javadoc) style comments.

Code:

/**
 * This is a function. It does this this and that. Here is what is expected
 * from the parameters, what to expect for the output, what causes errors,
 * what guarentees can be made, etc..
 *
 * \param a The letter a
 * \param b The letter b
 * \return The letter c
 */
char some_func(char a, char b) {
    return 'c';
}

I don't use comments too much inside the functions, except where necessary. However, inside the function, I like to use slashies (//), since you can then comment out huge sections of code with comment blocks, and not worry about syntax errors.

Code:

/* Nasty old, ugly way of doing that

// this does that
this.doThat();

//more stuff ... here

*/


ta0kira 02-23-2008 03:36 PM

Box comments are painful to maintain, so I avoid them. I normally don't even use /**/ comments unless I have a paragraph to write. I generally comment between a function name or conditional and its {} with the purpose of the function or condition, but only if it's significant and then only one line. If there's something that I know I as the maintainer will wonder about later, I use a //NOTE:. I rarely use a multi-line comment unless it's in an API header. Sometimes I'll block off a class or function like this:
Code:

//Class my_class--------------------------------------------
//class for holding my_objects
class my_class
{
public:
        int my_function(bool) const;
        //find out a mysterious value*
        //yes/no, returns mysterious value
}; //END my_class-------------------------------------------

//*even this type is a lot of work to keep track of

Most comments are meant for the maintainer, so write and format them in ways that draw your attention and explain what you need to remember. You only need basic comments for API headers since you should also have some sort of documentation. Also, it's a real pain to track down a header just to look up a function (I have to do that with the STL sometimes if I'm not online,) so don't count on the header to document classes and functions. Also, it's even more of a pain to update several sets of comments for the same thing when you change it (such as its name, arguments, or internal functioning.) Each of those pieces of info should be in one place and the other places should refer to that one place (normally that place is the documentation.)
ta0kira

JWPurple 02-23-2008 05:17 PM

Comments are most useful if they're short, in plain english, and accurate. That way they're more likely to be updated as the program gets modified.

In other words, pay more attention to what you put in them than how they look.

ta0kira 02-23-2008 07:51 PM

Quote:

Originally Posted by JWPurple (Post 3067635)
Comments are most useful if they're short, in plain english, and accurate. That way they're more likely to be updated as the program gets modified.

In other words, pay more attention to what you put in them than how they look.

Additionally, if you need a lot of comments then that means the code itself could use some clearer formatting or design.
ta0kira

JWPurple 02-23-2008 08:10 PM

Quote:

Originally Posted by JWPurple (Post 3067635)
... in plain english ...

I'm showing my limited view of the world (from the US). :o Of course they could be in plain Mandarin if that's appropriate for the maintainers!

paulsm4 02-23-2008 10:50 PM

Quote:

Comments are most useful if they're short, [plainly written], and accurate...

In other words, pay more attention to what you put in them than how they look.
Amen! I agree completely!

Two additional notes:
1. Comments should always be "at the level of intent"
<= "What" you're doing should be obvious from the code
So the comment should (briefly!) explain the "why"
In other words: what is the *goal* of this block of code?

2. Although it's not so much important how comments look...
... it *is* important to be *consistent* in how they look.

This is the reason for coding standards - to insure consistency.

ta0kira 02-24-2008 02:46 AM

There needs to be some sort of auto-commenting IDE plug-in where you select a function name and it lets you fill in a few fields, then it adds or edits the comments based on your own style. Also, something like OpenOffice styles where you can change the master style definition and it will update it everywhere.
ta0kira

jlliagre 02-24-2008 05:58 AM

Quote:

Originally Posted by JWPurple (Post 3067748)
Of course they could be in plain Mandarin if that's appropriate for the maintainers!

I definitely prefer dealing with poorly written 'global' English comment than a native one (even in my own mother tongue), as the programming languages and their libraries are already 99.99% in English. Mixing languages often lead to confusion.
Moreover, one never knows who is going to maintain a piece of code in the future in these foreign outsourcing times ...

JMJ_coder 02-25-2008 08:23 PM

Hello,

Quote:

Originally Posted by 95se (Post 3067524)
Well, I comment ALL functions (/methods), usually using doxygen (or Javadoc) style comments.

Code:

/**
 * This is a function. It does this this and that. Here is what is expected
 * from the parameters, what to expect for the output, what causes errors,
 * what guarentees can be made, etc..
 *
 * \param a The letter a
 * \param b The letter b
 * \return The letter c
 */
char some_func(char a, char b) {
    return 'c';
}

I don't use comments too much inside the functions, except where necessary. However, inside the function, I like to use slashies (//), since you can then comment out huge sections of code with comment blocks, and not worry about syntax errors.

Code:

/* Nasty old, ugly way of doing that

// this does that
this.doThat();

//more stuff ... here

*/


Thanks. That example for the pre-function comments looks like a very good system. And it looks like an excellent approach to what to include in the comments.

JMJ_coder 02-25-2008 08:24 PM

Hello,

Quote:

Originally Posted by ta0kira (Post 3067739)
Additionally, if you need a lot of comments then that means the code itself could use some clearer formatting or design.
ta0kira

Thanks, that is some good advice.

jtshaw 02-25-2008 08:42 PM

Quote:

Originally Posted by JMJ_coder (Post 3069696)
Hello,
Thanks, that is some good advice.

It is good advice. In general if you find yourself putting a lot of internal comments inside a function perhaps you need to ask yourself if the function itself is too complex for its own good. I reserve interior function comments for special occasions when I'm using complex math or something of that nature.

As for all other comments... I typically only put comments in the header files (with my class definitions or function prototypes) and I use the Doxygen format so I can easily create decent developer documentation.

sundialsvcs 02-25-2008 10:56 PM

My "comment style?"

Easy.

"Clear."

Honestly, I really don't care how you prefer to do it. Over the years I've read and worked-with code that runs the full gamut of programmer personal-preferences. I do prefer that you "pick a style and stick with it," but I frankly don't care too much what that style might be. Stylistic peculiarities will not affect me.

What will "affect me" is the time that I waste trying to deduce the designer's intent.

Quote:

"Talk to me. Please. Just you and me. Just talk. Tell me what's going on in your head right now, as you write this code that I am (years later...) reading now."
You see, there's a part of what you wrote that was aimed at the computer, and another part of what you wrote that was aimed at (you and...) me. The part that's aimed at the computer is still there... same as it ever was... but that's not the part that I fail to understand. Hey, I'm sorry that you're dead now, having been smooshed by that unfortunate bread-truck, but I really do still need to "talk to you." I need to understand, as quickly and as accurately as possible, exactly what you were thinking when you wrote that bit of code.


All times are GMT -5. The time now is 05:57 PM.