search

Home  >  Q&A  >  body text

c++ - 三元运算符 a = b ?: c 是什么意思

注意:我很清楚 a = b ? c : d 是什么意思,可这不是我要问的问题。

三元运算符 a = b ?: c 是什么意思。注意, ?和: 是在一起的

高洛峰高洛峰2803 days ago1269

reply all(5)I'll reply

  • PHP中文网

    PHP中文网2017-04-17 12:00:50

    Help you search, see StackOverflow

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 12:00:50

    a = b ?: c is the abbreviation of a = b ? b : c.

    reply
    0
  • 黄舟

    黄舟2017-04-17 12:00:50

    b = true
    c = false
    a = b ?: c  // a = true
    
    b = false
    c = true
    a = b ?: c // a = true
    

    reply
    0
  • ringa_lee

    ringa_lee2017-04-17 12:00:50

    Although the title of the question is tagged C and C++, I wrote a PHP script to test it, and the results are as follows:

    php<?php
    $b = true;
    $c = false;
    $a = $b ?: $c;
    var_dump($a); // 输出true
    
    $b = false;
    $c = true;
    $a = $b ?: $c;
    var_dump($a); // 输出true
    

    From the output result, the meaning of a = b ?: c is: if b is true, then a = b, if b is false, then a = c

    reply
    0
  • 伊谢尔伦

    伊谢尔伦2017-04-17 12:00:50

    The format should be

    (boolean expression) ? a : b

    If the content of the boolean expression is true, then a.
    If the content of the boolean expression is false, then b.

    For example:

    javapublic int test(int a) {
        if (a > 0) {
            return 1;
        } else {
            return -1;
        }
    }
    

    The above if-else can be replaced by ternary operation, as follows:

    java    public int test(int a) {
            return (a > 0) ? 1 : -1;
        }
    

    reply
    0
  • Cancelreply