How do I use the conditional operator?

后端 未结 9 1040
忘了有多久
忘了有多久 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;
    

提交回复
热议问题