C语言 C 中的 IF-ELSE 语句快捷方式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18646190/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
IF-ELSE statement shortcut in C
提问by sherrellbc
C has the following syntax for a shorthand IF-ELSE statement
C 具有以下速记 IF-ELSE 语句的语法
(integer == 5) ? (TRUE) : (FALSE);
I often find myself requiring only one portion (TRUE or FALSE) of the statement and use this
我经常发现自己只需要语句的一部分(TRUE 或 FALSE)并使用它
(integer == 5) ? (TRUE) : (0);
I was just wondering if there was a way to not include the ELSE portion of the statement using this shorthand notation?
我只是想知道是否有一种方法可以使用这种速记符号不包含语句的 ELSE 部分?
采纳答案by Jeremy
The operator ?:must return a value. If you didn't have the "else" part, what would it return when the boolean expression is false? A sensible default in some other languages may be null, but probably not for C. If you just need to do the "if" and you don't need it to return a value, then typing ifis a lot easier.
运算符?:必须返回一个值。如果你没有“else”部分,当布尔表达式为假时它会返回什么?其他一些语言中合理的默认值可能是 null,但对于 C 可能不是。如果您只需要执行“if”并且不需要它来返回值,那么键入if会容易得多。
回答by David M W Powers
Question is whether we can somehow write the following expression without both then and else parts
问题是我们是否可以在没有 then 和 else 部分的情况下以某种方式编写以下表达式
(integer == 5) ? (THENEXPR) : (ELSEEXPR);
(integer == 5) ? (THENEXPR) : (ELSEEXPR);
If you only need the then part you can use &&:
如果您只需要 then 部分,您可以使用&&:
(integer == 5) && (THENEXPR)
(integer == 5) && (THENEXPR)
If you only need the else part use ||:
如果您只需要 else 部分,请使用 ||:
(integer == 5) || (ELSEEXPR)
(integer == 5) || (ELSEEXPR)

