Mushy
Mushy

Reputation: 2655

Conditional Operator: How much flexibility?

I would like to perform the following:

if(x == true)
{
    // do this on behalf of x
    // do this on behalf of x
    // do this on behalf of x
}

Using a conditional operator, is this correct?

x == true ? { /*do a*/, /*do b*/, /*do c*/ } : y == true ? ... ;

Is this malformed?

I am not nesting more than one level with a conditional operator.

The expressions I intend to use are highly terse and simple making a conditional operator, in my opinion, worth using.

P.S. I am not asking A. Which I should use? B. Which is better C. Which is more appropriate

P.S. I am asking how to convert an if-else statement to a ternary conditional operator.

Any advice given on this question regarding coding standards etc. are simply undesired.

Upvotes: 0

Views: 108

Answers (3)

Jan Herrmann
Jan Herrmann

Reputation: 2767

Of course it works (with C++11). I have not tried a solution but following Herb Sutters way you can use ether a function call or a lambda which is immediately executed:

cond ? 
  [&]{
    int i = some_default_value;
    if(someConditionIstrue)
    {
        Do some operations ancalculate the value of i;
        i = some calculated value;
    }
    return i;
} ()  
  : 
somefun() ;

I have not tried to compile it but here you have an result whih is either computed with an lambda or an normal function.

Upvotes: 0

Mats Petersson
Mats Petersson

Reputation: 129524

Using comma operator to string different expressions together is within the rules of the language, but it makes the code harder to read (because you have to spot the comma, which isn't always easy, especially if the expression isn't really simple.

The other factor is of course that you can ONLY do this for if (x) ... else if(y) ... type conditionals state.

Sometimes, it seems like people prefer "short code" from "readable code", which is of course great if you are in a competition of "who can write this in the fewest lines", but for everything else, particularly code that "on show" or shared with colleagues that also need to understand it - once a software project gets sufficiently large, it usually becomes hard to understand how the code works WITHOUT obfuscation that makes the code harder to read. I don't really see any benefit in using conditional statements in the way your second example described. It is possible that the example is bad, but generally, I'd say "don't do that".

Upvotes: 1

john
john

Reputation: 8027

Don't compare booleans to true and false. There's no point because they're true or false already! Just write

if (x)
{
    // do this on behalf of x
    // do this on behalf of x
    // do this on behalf of x
}

Your second example doesn't compile because you use { and }. But this might

x ? ( /*do a*/, /*do b*/, /*do c*/ ) : y ? ... ;

but it does depend on what /*do a*/ etc are.

Upvotes: 3

Related Questions