Question

I heard about a kind of If statement which use ? and : in C
I dont know how to use it and I cant find anything about it. I need to use it in order to shorten my code any help would be appreciated.

Was it helpful?

Solution

?: is ternary operator in C (also called conditional operator). You can shorten your code like

if(condition)
    expr1;
else
    expr2;  

to

condition ? expr1 : expr2;   

See how it works:

C11: 6.5.15 Conditional operator:

The first operand is evaluated; there is a sequence point between its evaluation and the evaluation of the second or third operand (whichever is evaluated). The second operand is evaluated only if the first compares unequal to 0; the third operand is evaluated only if the first compares equal to 0; the result is the value of the second or third operand (whichever is evaluated),

OTHER TIPS

As others have mentioned, it's called the ternary operator. However, if you didn't know that, it would be somewhat difficult to Google it directly since Google doesn't handle punctuation well. Fortunately, StackOverflow's own search handles punctuation in quotes for exactly this kind of scenario.

This search would yield the answer you were looking for. Alternately, you could search for "question mark and colon in c" on Google, spelling out the name of the punctuation.

First you have the condition before the ?

Then you have the expression for TRUE between ? and :

Then you have the expression for FALSE after :

Something like this:

(1 != 0) ? doThisIfTrue : doThisIfFalse

The ternary operator ?: is a minimize if statement which can reduce this:

if(foo)
    exprIfTrue();
else
    exprIfFalse();

To this:

(foo) ? exprIfTrue() : exprIfFalse() ;

Personally, I avoid using it because it easily becomes unreadable. The only good example of use is to display the status of a flag in a printf:

int my_flag = 1;

printf("My flag: %s\n", my_flag ? "TRUE" : "FALSE" );
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top