Operator precedence and ternary operator

后端 未结 2 1021
既然无缘
既然无缘 2021-01-16 10:48

I have a problem in C.

#include
int main()
{
    int a = 10, b = 0, c = 7;
    if (a ? b : c == 0)
        printf(\"1\");
    else if (c = c |         


        
相关标签:
2条回答
  • 2021-01-16 11:05

    Your conditions are not properly written.

    In the first if-statement:

      if (a ? b : c == 0)
    

    if you put the values, then it becomes

    if(10 ? 0 : 7 == 0)
    

    means, it will always return 0.

    That's why control goes to the else part and there, it becomes

    else if (7 = 7 || 10 && 0)
    

    since you used the "=" operator here (c = c), it will be always true, therefore it prints "2".

    Now you want that code should return "1", then change your if statement in this way.

     if( (a ? b:c) == 0){...}
    

    because "==" operator has higher precedence than ternary operator.

    0 讨论(0)
  • 2021-01-16 11:14

    The conditional operator (?:) has one of the lowest precedences. In particular it is lower than ==. Your statement means this:

    if(a ? b : (c == 0)) { ... }
    

    Not this:

    if((a ? b : c) == 0) { ... }
    
    0 讨论(0)
提交回复
热议问题