How do I use the conditional operator?

后端 未结 9 940
忘了有多久
忘了有多久 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:03

    It works like this:

    (condition) ? true-clause : false-clause
    

    It's most commonly used in assignment operations, although it has other uses as well. The ternary operator ? is a way of shortening an if-else clause, and is also called an immediate-if statement in other languages (IIf(condition,true-clause,false-clause) in VB, for example).

    For example:

    bool Three = SOME_VALUE;
    int x = Three ? 3 : 0;
    

    is the same as

    bool Three = SOME_VALUE;
    int x;
    if (Three)
        x = 3;
    else
        x = 0;
    

提交回复
热议问题