shorthand c++ if else statement

后端 未结 4 529
梦毁少年i
梦毁少年i 2020-12-09 17:23

So I\'m just curious if there is a short hand statement to this:

if(number < 0 )
  bigInt.sign = 0;
else
  bigInt.sign = 1;

I see all th

相关标签:
4条回答
  • 2020-12-09 17:39

    The basic syntax for using ternary operator is like this:

    (condition) ? (if_true) : (if_false)
    

    For you case it is like this:

    number < 0 ? bigInt.sign = 0 : bigInt.sign = 1;
    
    0 讨论(0)
  • 2020-12-09 17:46

    try this:

    bigInt.sign = number < 0 ? 0 : 1
    
    0 讨论(0)
  • 2020-12-09 18:00

    Yes:

    bigInt.sign = !(number < 0);
    

    The ! operator always evaluates to true or false. When converted to int, these become 1 and 0 respectively.

    Of course this is equivalent to:

    bigInt.sign = (number >= 0);
    

    Here the parentheses are redundant but I add them for clarity. All of the comparison and relational operator evaluate to true or false.

    0 讨论(0)
  • 2020-12-09 18:01

    Depending on how often you use this in your code you could consider the following:

    macro

    #define SIGN(x) ( (x) >= 0 )
    

    Inline function

    inline int sign(int x)
    {
        return x >= 0;
    }
    

    Then you would just go:

    bigInt.sign = sign(number); 
    
    0 讨论(0)
提交回复
热议问题