Alex Rivera | Logout

Best practices: Where should function comments go in C/C++ code?

Asked 2009-12-04T22:12:31.457
21

So... I understand this might be subjective, but I'd like some opinions on what the best practice for this is.

Say I have the following header and .cpp file:

header:

// foo.h

class foo
{
public:
    int bar(int in);
};

cpp:

// foo.cpp

int foo::bar(int in)
{
    // some algorithm here which modifies in and returns the modified value
}

Now say I have this function comment:

/* 
    input:    an integer as input to algorithm foo

    output:   The result of the algorithm foo on input in

    remarks:  This function solves P = NP
*/

Would best practice be to place this function comment in the header above the function declaration or above the function definition in the cpp file? Thanks SO

c++ c
Edit
Report

2 Answers

2

It's like asking what the best practices for putting your socks on is. Some tools have a better chance to work if you put the declaration and comment together and that probably makes the most sense as to what people expect. But commenting randomly is pointless. Having in/out stuff especially, unless you have a tool which uses that. Any programmer can see what he or she needs from the declaration, and same applies to the language in general. Nothing is more useless than comments like //this is the constructor.

Rather try to keep the code itself as simple as possible with names that make sense and a general organization to the code and if there is anything strange write a real paragraph about it like //We had to do this because some weird api we use requires certain things //that caused some other things to break and calls to it get optimized out sometimes //so don't take out these method calls or the optimizer optimizes out //some other stuff and the whole program stops working

answered 2009-12-04T23:20:24.597
1

Because I have always used Visual Assist X, and have the ability to jump around code very easily, I use the header file as an index. That is, the header file contains only the relevant data with no additional comments as not to add bloat to the file. If the reader wants further information on the function they can jump to the cpp.

This of course assumes that all people that read your code will have the same thought process, which is false. It is nice to only have bloat in one file though.

answered 2009-12-04T22:55:38.703

Your Answer