Unexpected Result, Ternary Operator in Gnu C

前端 未结 2 815
春和景丽
春和景丽 2021-01-25 02:54

So the operator precedence of the ternary operator in C seems truly bizarre to me. Case in point:

#include 

int main ()
{
   int i=5         


        
相关标签:
2条回答
  • 2021-01-25 03:46

    What is weird here? The first part is interpreted as:

    (11 + (k != 7)) ? 1 : 11
    

    and the second is interpreted as

     11 + ((k !=7) ? 1 :11)
    

    The first is caused by the precedence rules (binary arithmetic has higher precedence than the ternary operator) and the second circumvents the precedence rules through grouping the expression with parenthesis.

    Your edit asks for the reasons and one can usually only guess at those unless someone on the C committee who was present at the time comes around to help. My guess would be that it is much more common to use a complex expression and ask for its truth value than using the ternary operator to determine the value of an expression in arithmetic. Something like this comes to mind:

    return (froble() + 3) == 0 ? 23 : 5; // parens for sanity but works without
    

    if this would be interpreted as return (froble() + 3) == 5; I would be truly shocked.

    0 讨论(0)
  • 2021-01-25 03:50

    One should pick a very high or very low precedence, and one or the other will be surprising to someone who makes the wrong assumption.

    A useful reason for choosing low precedence is that it means that the operator functions like an if .. then .. else .. construct without any braces, which might mean less work for compiler writers (who might use the same code to handle both), and straightforward refactoring by coders who understand the precedence.

    In practice, the language probably standardised whatever precedence was the most popular usage in code written in the pre-standardization era.

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