How do I use the conditional operator?

后端 未结 9 933
忘了有多久
忘了有多久 2020-11-22 16:27

I\'ve always wondered how to write the \"A ? B : C\" syntax in a C++ compatible language.

I think it works something like: (Pseudo

相关标签:
9条回答
  • 2020-11-22 17:12

    No one seems to mention that a result of conditional operator expression can be an L-value in C++ (But not in C). The following code compiles in C++ and runs well:

        int a, b;
        bool cond;
        a=1; b=2; cond=true;
        (cond? a : b) = 3;
        cout << a << "," << b << endl;
    

    The above program prints 3, 2

    Yet if a and b are of different types, it won't work. The following code gives a compiler error:

        int a;
        double b;
        bool cond;
        a=1; b=2; cond=true;
        (cond? a : b) = 3;
        cout << a << "," << b << endl;
    
    0 讨论(0)
  • 2020-11-22 17:20

    I would say the ? is a short-cut. However, some "hard-core" programmers tend to say write it out the long way so in future cases, people can easily read and modify code.

    For example, if you write

    int a = b<c ? b : c;
    

    Some people claim that it's clearer to write:

    if(b<c)
     a = b;
    else
     a = c;
    

    Because in future cases, people can catch it. Of course, a simple b<c ? b:c is easy to catch, but sometimes complex operations are put in and it can be hard to spot.

    0 讨论(0)
  • 2020-11-22 17:24

    IT IS QUITE SIMPLE IT'S BASIC SYNTAX IS: expression1?expression2:expression3;

    If expression 1 is hold true then expression 2 will hold otherwise expression 3 will hold.

    example:

    hey=24>2?24:34;

    here as condition is true value of 24 will be assigned to it. if it was false then 34 will be assigned to it

    0 讨论(0)
提交回复
热议问题