【问题标题】:Can I use more than one instruction in the second or third operand of the ternary operator?我可以在三元运算符的第二个或第三个操作数中使用多个指令吗?
【发布时间】:2015-07-22 18:55:44
【问题描述】:

我可以做一些非常相似的东西吗?

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

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

【问题讨论】:

  • 是的,使用括号和逗号运算符。
  • 经验法则:不要将?: 用于控制流。
  • 或者避免它,让它可读(即使你在质疑逗号运算符的用法)
  • 只需将其替换为if-else。问题解决了,可读性提高了。

标签: c++ ternary-operator


【解决方案1】:

如果通过“指令”(就 C++ 的措辞而言,这甚至不是一个东西),你的意思是“表达式”,那么当然:括号和逗号运算符来拯救!

SSCCE:

#include <cstdio>

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

【讨论】:

  • 这是一个奇怪的例子,因为逗号操作数没有副作用。您的代码相当于int x = 0 ? 3 : 5;。为什么printf 在 C++ 问题中?
  • @ChristianHackl 没有任何副作用有什么问题?它仍然是一个表达式(因此它展示了 OP 问题的答案),不是吗?至于printfit's far superior to trying to shift a stream to the left
  • 副作用是首先使用逗号运算符的唯一原因。
  • @ChristianHackl 如果您遵循上面的好建议(关于完全避免不必要的“聪明”代码),那么副作用是不使用逗号的另一个原因操作员。无论如何,无论它们是否是一个原因——我的例子仍然回答了 OP 的问题。
  • 我不明白。您是否故意发布了一个逗号运算符没有意义的示例,只是为了强调不应将其用于控制​​流这一事实?
【解决方案2】:

是的,看看下面的例子:

#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;
}

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

【讨论】:

  • 请注意,如对原始问题的评论中所述,括号是必不可少的,特别是在三元运算符的第三个参数周围。没有它们,第一个逗号之后的所有内容都会被解释为跟随三元而不是它的一部分。见stackoverflow.com/questions/9189522/…
【解决方案3】:

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

【讨论】:

    【解决方案4】:

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

    所以我用 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;
    }
    

    【讨论】:

      猜你喜欢
      • 2013-09-11
      • 1970-01-01
      • 2016-04-13
      • 1970-01-01
      • 2018-04-22
      • 1970-01-01
      • 1970-01-01
      • 2019-10-08
      • 2012-12-30
      相关资源
      最近更新 更多