nedward
nedward

Reputation: 478

Is it possible to use another conditional expression inside a conditional expression?

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

Answers (2)

Marievi
Marievi

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

Loay Ashmawy
Loay Ashmawy

Reputation: 687

Yes but you must use parenthesis like so:

a == 1?a += 1:(a == 0?a += 2:a = 3);

Upvotes: 0

Related Questions