If statement with? and:

Have I heard of some If statement using ? and : in C
I do not know how to use it, and I can not find anything about it. I need to use it to shorten the code any help would be appreciated.

+6
source share
4 answers

?: ternary operator in C (also called a conditional operator). You can shorten the code, for example

 if(condition) expr1; else expr2; 

to

 condition ? expr1 : expr2; 

See how it works:

C11: 6.5.15 Conditional statement:

The first operand is evaluated; between its evaluation and the point, the evaluation of the second or third operand (depending on what is being evaluated). The second operand is evaluated only if the first comparison is uneven with 0 ; the third operand is evaluated only if the first is compared to 0 ; the result is the value of the second or third operand (depending on what is being evaluated),

+10
source

As already mentioned, he was called a ternary operator. However, if you did not know this, it would be rather difficult for Google, since Google does not cope with punctuation. Fortunately, StackOverflow’s own search handles quotation marks for that particular scenario.

This search will give the answer you were looking for. Alternatively, you can find the “question mark and colon in c” on Google with a punctuation name.

+3
source

First you have a condition before?

Then do you have an expression for TRUE between? and:

Then you have an expression for FALSE after:

Something like that:

 (1 != 0) ? doThisIfTrue : doThisIfFalse 
0
source

The ternary operator ?: Is an if minimization if that can reduce this:

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

For this:

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

Personally, I do not use it, because it easily becomes unreadable. The only good use case is displaying the status of a flag in printf :

 int my_flag = 1; printf("My flag: %s\n", my_flag ? "TRUE" : "FALSE" ); 
0
source

All Articles