If statement with ? and : [duplicate]

亡梦爱人 提交于 2019-12-19 18:52:29

问题


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.


回答1:


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




回答2:


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.




回答3:


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



回答4:


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" );


来源:https://stackoverflow.com/questions/20887012/if-statement-with-and

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!