Unexpected Result, Ternary Operator in Gnu C

前端 未结 2 859
春和景丽
春和景丽 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    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.

提交回复
热议问题