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.
相关问题
- Multiple sockets for clients to connect to
- What is the best way to do a search in a large fil
- glDrawElements only draws half a quad
- Index of single bit in long integer (in C) [duplic
- Equivalent of std::pair in C
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.
?:
is ternary operator in C (also called conditional operator). You can shorten your code liketo
See how it works:
C11: 6.5.15 Conditional operator:
The ternary operator
?:
is a minimizeif
statement which can reduce this:To this:
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
: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: