Reputation: 478
I was wondering about the "? :" operators in C. Can one use the conditional operator inside another conditional operator like this?
int a = 0;
a == 1?a += 1:a == 0?a += 2:a = 3;
This is a very bad example, but I hope you understand what I'm trying to ask.
Upvotes: 0
Views: 117
Reputation: 5009
Of course you can, like this :
int a = 0;
a == 1?(a += 1):((a == 0)?(a += 2):(a = 3));
It is the same as writing :
int a = 0;
if (a == 1)
a += 1;
else
if (a == 0)
a += 2;
else
a = 3;
which is much more clear to read and understand.
Upvotes: 1
Reputation: 687
Yes but you must use parenthesis like so:
a == 1?a += 1:(a == 0?a += 2:a = 3);
Upvotes: 0