Reputation: 373
What's the standard line to add to the ternary operator in order to do nothing if the condition is not met?
Example:
int a = 0;
a > 10 ? a = 5 : /*do nothing*/;
Using a
seems to do the trick, but I am wondering if there is a more generally accepted way.
Upvotes: 7
Views: 14915
Reputation: 3640
Just for a sake of variety, but not recommending as it is very ambiguous.
void do_smth()
{}
bool a = true; // not necessarily
a && (do_smth(), 0);
Upvotes: 0
Reputation: 336
You can also use a logical expression (though maybe confusing) in case you don't want to use an if statement.
a > 10 && a = 5
Upvotes: 4
Reputation: 96286
Another option:
a ? void(a = 0) : void();
What's good about this one is that it works even if you can't construct an instance of decltype(a = 0)
to put into the 'do nothing' expression. (Which doesn't matter for primitive types anyway.)
Upvotes: 6
Reputation: 2790
You can do:
a > 10 ? a=5 : 0;
But, I would prefer:
if (a > 10)
a = 5;
Upvotes: 0
Reputation: 680
That will do it:
a = a > 10 ? 5 : a;
or simply:
if (a > 10) a = 5;
Upvotes: 21