comma operator in if condition

后端 未结 2 971
死守一世寂寞
死守一世寂寞 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:01

    Here is an example, provided by wikipedia, which shows another use case:

    The comma can be used within a condition (of an if, while, do while, or for) to allow auxiliary computations, particularly calling a function and using the result, with block scoping:

    if (y = f(x), y > x) { ... // statements involving x and y }

    // See this Wikipedia discussion

    Many C programmers have encountered the comma in the initializer part of a for statement, but not as many have seen it used in an if statement. In the case above it allows you to initialize y before the if statement tests the condition y>x.

提交回复
热议问题