LinuxQuestions.org
Latest LQ Deal: Latest LQ Deals
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 02-23-2008, 11:47 AM   #1
JMJ_coder
Member
 
Registered: Apr 2006
Distribution: Fedora
Posts: 478

Rep: Reputation: 30
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())?
 
Old 02-23-2008, 01:26 PM   #2
H_TeXMeX_H
LQ Guru
 
Registered: Oct 2005
Location: $RANDOM
Distribution: slackware64
Posts: 12,928
Blog Entries: 2

Rep: Reputation: 1301Reputation: 1301Reputation: 1301Reputation: 1301Reputation: 1301Reputation: 1301Reputation: 1301Reputation: 1301Reputation: 1301Reputation: 1301
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		  */
/*							  */
/**********************************************************/
 
Old 02-23-2008, 02:54 PM   #3
osor
HCL Maintainer
 
Registered: Jan 2006
Distribution: (H)LFS, Gentoo
Posts: 2,450

Rep: Reputation: 78
Quote:
Originally Posted by JMJ_coder View Post
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.
 
Old 02-23-2008, 03:15 PM   #4
95se
Member
 
Registered: Apr 2002
Location: Windsor, ON, CA
Distribution: Ubuntu
Posts: 740

Rep: Reputation: 32
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

*/
 
Old 02-23-2008, 03:36 PM   #5
ta0kira
Senior Member
 
Registered: Sep 2004
Distribution: FreeBSD 9.1, Kubuntu 12.10
Posts: 3,078

Rep: Reputation: Disabled
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
 
Old 02-23-2008, 05:17 PM   #6
JWPurple
Member
 
Registered: Feb 2008
Posts: 67

Rep: Reputation: 17
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.
 
Old 02-23-2008, 07:51 PM   #7
ta0kira
Senior Member
 
Registered: Sep 2004
Distribution: FreeBSD 9.1, Kubuntu 12.10
Posts: 3,078

Rep: Reputation: Disabled
Quote:
Originally Posted by JWPurple View Post
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
 
Old 02-23-2008, 08:10 PM   #8
JWPurple
Member
 
Registered: Feb 2008
Posts: 67

Rep: Reputation: 17
Quote:
Originally Posted by JWPurple View Post
... in plain english ...
I'm showing my limited view of the world (from the US). Of course they could be in plain Mandarin if that's appropriate for the maintainers!
 
Old 02-23-2008, 10:50 PM   #9
paulsm4
LQ Guru
 
Registered: Mar 2004
Distribution: SusE 8.2
Posts: 5,863
Blog Entries: 1

Rep: Reputation: Disabled
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.
 
Old 02-24-2008, 02:46 AM   #10
ta0kira
Senior Member
 
Registered: Sep 2004
Distribution: FreeBSD 9.1, Kubuntu 12.10
Posts: 3,078

Rep: Reputation: Disabled
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
 
Old 02-24-2008, 05:58 AM   #11
jlliagre
Moderator
 
Registered: Feb 2004
Location: Outside Paris
Distribution: Solaris 11.4, Oracle Linux, Mint, Debian/WSL
Posts: 9,789

Rep: Reputation: 492Reputation: 492Reputation: 492Reputation: 492Reputation: 492
Quote:
Originally Posted by JWPurple View Post
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 ...
 
Old 02-25-2008, 08:23 PM   #12
JMJ_coder
Member
 
Registered: Apr 2006
Distribution: Fedora
Posts: 478

Original Poster
Rep: Reputation: 30
Hello,

Quote:
Originally Posted by 95se View Post
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.
 
Old 02-25-2008, 08:24 PM   #13
JMJ_coder
Member
 
Registered: Apr 2006
Distribution: Fedora
Posts: 478

Original Poster
Rep: Reputation: 30
Hello,

Quote:
Originally Posted by ta0kira View Post
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.
 
Old 02-25-2008, 08:42 PM   #14
jtshaw
Senior Member
 
Registered: Nov 2000
Location: Seattle, WA USA
Distribution: Ubuntu @ Home, RHEL @ Work
Posts: 3,892
Blog Entries: 1

Rep: Reputation: 67
Quote:
Originally Posted by JMJ_coder View Post
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.
 
Old 02-25-2008, 10:56 PM   #15
sundialsvcs
LQ Guru
 
Registered: Feb 2004
Location: SE Tennessee, USA
Distribution: Gentoo, LFS
Posts: 10,665
Blog Entries: 4

Rep: Reputation: 3945Reputation: 3945Reputation: 3945Reputation: 3945Reputation: 3945Reputation: 3945Reputation: 3945Reputation: 3945Reputation: 3945Reputation: 3945Reputation: 3945
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.

Last edited by sundialsvcs; 02-25-2008 at 10:57 PM.
 
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
How to know if I am using mbox-style or maildir-style? Niceman2005 Linux - General 1 09-23-2005 12:08 PM
VIM-style wrapping to OpenOffice style schmmd Linux - Software 1 12-21-2004 06:50 PM
how to change mandrake style menu to kde style menu msalimane Mandriva 1 12-07-2004 01:16 PM
Just a comment... arobic Linux - Newbie 20 08-22-2003 01:46 PM
comment wardrazer *BSD 2 07-14-2003 08:22 AM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

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

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration