我可以在三元运算符的第二个或第三个操作数中使用多个指令吗?

Can I use more than one instruction in the second or third operand of the ternary operator?

我可以做类似这样的东西吗?

question ? func1(), val=5 : func2()

我想在第一个或第二个参数的位置放置多个指令。 可以解决吗?

如果 "instruction"(对于 C++ 的措辞来说,这甚至都不是问题),你的意思是 "expression",那么当然:括号和逗号运算符来拯救!

SSCCE:

#include <cstdio>

int main()
{
    int x = (1, 0) ? 2, 3 : (4, 5);
    printf("%d\n", x); // prints 5
}

是的,看看下面的例子:

#include <iostream>

int main()
{
    int x,y,z;
    double d = 2.5;


    auto f = (d == 2.2) ? (x=5,y=10,z=0,2000) : (x=15,y=0,z=20,1000);

    std::cout << x << " " << y << " " << z << " " << f << std::endl;


    std::cin.get();
    return 0;
}

不是很干净所以建议让它更具可读性。

http://www.cplusplus.com/forum/articles/14631/ 上有一个关于三元运算符的讨论讨论了这个问题。讨论的评论中有一些示例显示了三元运算符中函数调用和多个操作的用法。不过,为了清楚起见,最好不要在三元运算符中一次做太多事情——那样很快就很难阅读了。

感谢您提供这些快速而有用的答案!

所以我用 C++ 编写 Arduino,这是完整的示例代码:

void setup() {
  Serial.begin(115200);
  bool b = false;
  int val = 0;

  b ? func1() : (func2(), val = 2);

  Serial.println(val);
}

void loop() {}

void func1 (){
     Serial.println("func1");
}

void func2 (){
    Serial.println("func2");  
}

当我从这个答案中了解到如何正确使用方括号和逗号时,我遇到了这些错误:

sketch_jul22a.ino: In function 'void setup()':
sketch_jul22a:8: error: second operand to the conditional operator is of type 'void', but the third operand is neither a throw-expression nor of type 'void'
second operand to the conditional operator is of type 'void', but the third operand is neither a throw-expression nor of type 'void'

我用了int类型的函数而不是void类型,问题解决了:

int func1 (){
     Serial.println("func1");
     return 0;
}

int func2 (){
    Serial.println("func2");
    return 0;
}