Search code examples
c++coding-stylecommentsbraces

c++ curly braces and comments


C++ begginer here. I'm struggling a bit to get what's the best practice for curly braces + //comments.

I see that for functions comments above the definition provide Visual Studio inspection utility by hovering the mouse on them anywhere. But when it comes to if statements and the sorts, I can't figure out what will be best more helpful in upcoming projects

So, between

if (condition) {  // comment
    do something();
}

or

// comment
if (condition) {  
    do something();
}

or

if (condition) // comment
{  
    do something();
}

or even the following one (to use the that usually useless newline)

if (condition)
{  // comment
    do something();
}

there no clear "Ah this one is better because of xyz", to me yet.

Thank you for any foresight!

Cheers


Solution

  • This example may be handled differently depending on whether comment is applied to condition or to bock. First case typically indicates that condition may be rather complex and it would make sense to refactor it into separate variable or to separate method with proper naming so comment (if it is still necessary) will be applied to this variable or method. Second case typically indicates that you are doing something complex in that block and it would make sense to refactor block into separate method with proper naming so comment (if it is still necessary again) will be applied to this method. Notice that introduction of separate entities with proper names often completely removes need for a comment.

    As for curly braces there is no common approach, you can probably encounter all kind of crazy braces placement. Some people will even defend such pluralism. I prefer to place matching braces aligned - either horizontally (that is on the same line) or vertically (that is with same indentation) when content does not fit into one line. And this rule is applied to all braces, not just to curly.