Skip to content

Add rule ES.xx: Use the ternary operator '?' for conditional initialization #6

@peno2

Description

@peno2

I suggest to add a rule that explicitly mentions the use of the ternary operator '?', since using '?' in many cases can make the code a lot simpler compared to using a lambda expression or some initialisation function.
.
.
.
Use the ternary operator '?' for conditional initialization, in particular when the condition is simple enough to not justify the added complexity of using a lambda expression (ES.28). An important benefit of fully initializing an object is that it can be const-declared if so desired (see also ES.25).

Example
Here is an example that is often considered to demonstrate the difficulty to initialize objects direcltly at declaration.

widget w1;    // "widget" a type that's expensive to initialize, possibly a large POD
widget w2;

if (cond) {  // bad: w1 and w2 are initialized "late"
    w1 = f1();
    w2 = f2();
}
else {
    w1 = f3();
    w2 = f4();
}

Using the ternary operator '?' this can be rewritten to initialize both w1 and w2 at the time of declaration:

// good, properly initialized right away, may also be const now, if so desired
const widget w1 = cond ? f1(): f3();
const widget w2 = cond ? f2(): f4();

Or, as a matter of style, if this communicates the intent better, initialize both 'w1' and 'w2' in one single statement:

using std::pair;
const auto [w1,  w2]  = cond ?  pair{f1(), f2()}:  pair{f3(), f4()};    // C++17

.
.
.
Now, if the above suggestion is accepted some questions arises. How shall we handle ES.20 and ES.21 which both overlaps with the suggested rule to some extent?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions