The ternary (conditional) operator in C

2019-01-03 06:04发布

What is the need for the conditional operator? Functionally it is redundant, since it implements an if-else construct. If the conditional operator is more efficient than the equivalent if-else assignment, why can't if-else be interpreted more efficiently by the compiler?

15条回答
smile是对你的礼貌
2楼-- · 2019-01-03 06:37

The same as

if(0)
do();


if(0)
{
do();
}
查看更多
劫难
3楼-- · 2019-01-03 06:42

The ternary operator is a syntactic and readability convenience, not a performance shortcut. People are split on the merits of it for conditionals of varying complexity, but for short conditions, it can be useful to have a one-line expression.

Moreover, since it's an expression, as Charlie Martin wrote, that means it can appear on the right-hand side of a statement in C. This is valuable for being concise.

查看更多
该账号已被封号
4楼-- · 2019-01-03 06:42

In C, the real utility of it is that it's an expression instead of a statement; that is, you can have it on the right-hand side (RHS) of a statement. So you can write certain things more concisely.

查看更多
Viruses.
5楼-- · 2019-01-03 06:43

It's syntatic sugar and a handy shorthand for brief if/else blocks that only contain one statement. Functionally, both constructs should perform identically.

查看更多
来,给爷笑一个
6楼-- · 2019-01-03 06:44

ternary = simple form of if-else. It is available mostly for readability.

查看更多
我欲成王,谁敢阻挡
7楼-- · 2019-01-03 06:45

There are a lot of things in C that aren't technically needed because they can be more or less easily implemented in terms of other things. Here is an incomplete list:

  1. while
  2. for
  3. functions
  4. structs

Imagine what your code would look like without these and you may find your answer. The ternary operator is a form of "syntactic sugar" that if used with care and skill makes writing and understanding code easier.

查看更多
登录 后发表回答