comma operator in if condition

后端 未结 2 973
死守一世寂寞
死守一世寂寞 2020-12-05 07:49
int a = 1, b = 0;

if(a, b)
   printf(\"success\\n\");
else
   printf(\"fail\\n\");

if(b, a)
   printf(\"success\\n\");
else
   printf(\"fail\");

2条回答
  •  心在旅途
    2020-12-05 08:00

    http://en.wikipedia.org/wiki/Comma_operator:

    In the C and C++ programming languages, the comma operator (represented by the token ,) is a binary operator that evaluates its first operand and discards the result, and then evaluates the second operand and returns this value (and type).

    In your first if:

    if (a, b)
    

    a is evaluated first and discarded, b is evaluated second and returned as 0. So this condition is false.

    In your second if:

    if (b, a)
    

    b is evaluated first and discarded, a is evaluated second and returned as 1. So this condition is true.

    If there are more than two operands, the last expression will be returned.

    If you want both conditions to be true, you should use the && operator:

    if (a && b)
    

提交回复
热议问题