Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C/C++ function/method decoration

Tags:

c++

c

conventions

DISCLAIMER: I haven't done C++ for some time...

Is it common nowadays to decorate C/C++ function/method declarations in order to improve readability?

Crude Example:

void some_function(IN int param1, OUT char **param2);

with the macros IN and OUT defined with an empty body (i.e. lightweight documentation if you will in this example). Of course I understand this goes somewhat in parallel with the "doc comment block" associated with the method/function.

Could you provide some other examples... assuming this topic is useful to the community. Please bear in mind that the example above is just what it is.

like image 799
jldupont Avatar asked Oct 29 '09 19:10

jldupont


4 Answers

I wouldn't appreciate such decoration.

Much better to use const and references and constant references, like in

void some_function(AClass const &param1, AnotherClass &param2)

Usually int are passed by value and not by reference, so I used AClass and AnotherClass for the example. It seems to me that adding empy IN and OUT would be distracting.

like image 104
Francesco Avatar answered Oct 20 '22 23:10

Francesco


Windows headers actually do exactly this. See Header Annotations for the full list of annotations used. For example"

DWORD
WINAPI
GetModuleFileName(
    __in_opt HMODULE hModule,
    __out_ecount_part(nSize, return + 1) LPTSTR lpFilename,
    __in DWORD nSize
    );

For this function, hModule is an optional input parameter, lpFilename is an output parameter which store a maximum of nSize character elements and which will contain (the return value of the function)+1 character elements in it upon return, and nSize is an input parameter.

like image 27
Adam Rosenfield Avatar answered Oct 20 '22 22:10

Adam Rosenfield


For documentation purposes, a well-written comment block is sufficient, so these don't serve any purpose. Furthermore, some documentation comment parsers have special syntax for just such a thing; for example, given Doxygen, you could write:

/**
 * @param[in]  param1 ...
 * @param[out] param2 ...
 **/
void some_function(int param1, char **param2);
like image 6
Pavel Minaev Avatar answered Oct 20 '22 23:10

Pavel Minaev


I think this is a bad idea. Especially since anybody can come along and define the macros IN/OUT and leave you in heap big trouble.

If you really want to document it put comments in there.

void some_function(/* IN */ int param1, /* OUT */ char **param2);

Also why use an out when a return value will work fine.
Also I would prefer to use pass by ref and const ref to indicate my intentions. Also the compiler now does relatively good optimsing for intent when your code is const correct.

void some_function(/* IN */ int const& param1, /* OUT */ char*& param2);
// OK for int const& is kind of silly but other types may be usefull.
like image 4
Martin York Avatar answered Oct 20 '22 23:10

Martin York