3

Why can't the conditional operator be used as a statement?

I would like to do something like:

boolean isXyz = ...;
...
isXyz ? doXyz() : doAbc();

where doXyz and doAbc are return void.

Note that this is not the same as other operators, for example doXyz() + doAbc() intrinsically needs that doXyz and doAbc return a number-like something to operate (or strings to concatenate, or whatever, but the point is that + actually needs values to operate on).

Is there something deep or is it just an arbitrary decision.

Note: I come from the Java world, but I would like to know if this is possible in your favourite programming language.

4

7 回答 7

5

CC++允许这样的构造。只要doXyz()doAbc()返回的类型相同。包括void.

于 2009-09-03T10:25:04.340 回答
2

What would be the point? Why not just use an if statement (which, in my opinion, looks cleaner)?

于 2009-09-03T10:21:04.910 回答
1

作为一个新奇事物,mIRCscripting 允许您执行此操作

alias canI? {
   $iif($1 == 1,doThis,doThat)
}
alias doThis echo -a this can.
alias doThat echo -a that can.

/canI? 1用will echo调用它this can/canI? 2用will echo调用它that can

于 2009-09-03T10:25:08.553 回答
1

Because it would reduce readability and introduce a potential for errors.

Languages offer means of doing what you wish by using the keyword "if".

// Is not much longer than the line below
// but significantly more transparent
if (isXyz) doXyz() else doAbc();

isXyz ? doXyz() : doAbc();

A statement is supposed to just perform some operations.

A conditional operator is meant to return a value.

于 2009-09-03T10:19:48.020 回答
0

Wouldn't this be exactly the same as the if statement?

if (isXyz) doXyz(); else doAbc();

Some languages do allow you to use the conditional operator as a statement. Perl comes to mind.

于 2009-09-03T10:20:27.317 回答
0

一个表达式,包括一个条件表达式,可以单独用作 Java 和许多其他语言中的语句(我会说最流行的语言)。

这里的问题是Java中的“返回无效”,与条件无关。有时将活动(非幂等;具有副作用)代码隐藏在表达式中被认为是不好的品味,活动函数通常返回 void。因此,因为 Java 是一种规范性语言,它不允许在表达式中使用 void 函数。许多其他语言更宽松,并且会允许它。

你可以通过让 doAbc 和 doXyz 返回一些东西来绕过它——零、布尔值、任何东西:只要它们的类型相同,结果将在 ExpressionStatement 中被丢弃。但我真的不知道你为什么要这样做;正如其他人所说,这确实是在表达中做这件事的情况很差,而且在很大程度上毫无意义。

于 2009-09-03T11:11:30.580 回答
0

我认为你的问题是错误的方式......添加了条件运算符,因为“IF THEN”语句不能用作评估语句。

在我的选择中,您应该只在有条件地评估时使用条件运算符,因为它本质上不如在纯粹实现条件时使用“IF THEN”构造清晰。

条件运算符通常不能在每个条件结果上包含多条指令块,“IF THEN”可以。

于 2009-09-03T11:34:06.920 回答