Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If statement with ? and : [duplicate]

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.

like image 732
Amen Avatar asked Jan 02 '14 16:01

Amen


People also ask

Can you Vlookup with duplicates?

To find duplicates in Excel, you can use VLOOKUP to create a custom formula. If you have two lists, 1 and 2, and need to check for data across each, you use the formula =VLOOKUP(List-1, List-2,True,False). The List-1 data will be searched in List-2.


2 Answers

?: 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),

like image 103
haccks Avatar answered Oct 06 '22 20:10

haccks


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.

like image 41
1'' Avatar answered Oct 06 '22 20:10

1''