Skip to content
Takatoshi Kondo edited this page Feb 4, 2020 · 17 revisions

Case, Spacing, braces position, and so on.

#define SNAKE_CASE (1)

namespace snake_case {

//             east const
constexpr char const snake_case  = 0b00000010;

template <typename UpperCamelCase>
class snake_case {
public:
    void snake_case() {
        if (condition1) {
            // ...
        }
        else {
            // ...
        }

        switch (condition2) {
        case 1:
            // ...
            break;
        case 2:
            // ...
            break;
        case 3: {
            int local_variable = 1;
            // ...
        } break;
        }
    }
private:
    int snake_case_; // underscore postfix
};

} // namespace snake_case

Don't use negative comparison with else.

If condition has an else clause, condition should be positive. This rule is applied not only MACRO but also normal if-else.

// OK
#if defined(SOME_CONDITION)
    // do A
#else  // defined(SOME_CONDITION)
    // do B
#endif // defined(SOME_CONDITION)

// NG
#if !defined(SOME_CONDITION)
    // do B
#else  // !defined(SOME_CONDITION)
    // do A
#endif // !defined(SOME_CONDITION)

Conditional operator vs Lambda expression

Immediate invoking lambda expression is more preferred than conditional operator. If the types of return values are different, the lambda expression can declare the return type explicitly.

auto r = [&]() -> int {
    if (cond1 == 0) {
        if (cond2 == 0) {
            return 100;
        }
        return 200;
    }
    return 300;
} ();

Equivalent conditional operator. It is complicated.

int r = cond1 == 0 ? cond2 == 0 ? 100
                                : 200
                   : 300;

If the expression is simple enough, you can use conditional operator.