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.

- 154,301
- 39
- 440
- 740

- 1,524
- 5
- 22
- 41
-
11it is called the ternary operator - that should give you enough to google it – mathematician1975 Jan 02 '14 at 16:17
-
1I do not see a reason to down vote this question. Amen said clearly what he wants and why he wants it and that he cannot find answer to it otherwise. At least help him find the answer – trungdinhtrong Jan 02 '14 at 16:21
-
1if you type "? and : in c" in google you get "operators in c" wiki. you can find it there. – Koushik Shetty Jan 02 '14 at 16:24
-
1@Koushik if you type `"? and : in c"` into google filters out the punctuation, and you end up with a search that looks like `"and in c"` – Sam I am says Reinstate Monica Jan 02 '14 at 16:27
-
1@Koushik None of the first page of my Google results for that query have anything to do with the ternary operator. I assume it depends on your personalized results. – 1'' Jan 02 '14 at 16:27
-
1@SamIam @1" it is without the inverted commas. type without the filter.. – Koushik Shetty Jan 02 '14 at 16:30
4 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 to0
; the result is the value of the second or third operand (whichever is evaluated),

- 104,019
- 25
- 176
- 264
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

- 2,011
- 2
- 26
- 50
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" );

- 4,774
- 1
- 32
- 46