indira
indira

Reputation: 6687

comma operator in if condition

int a = 1, b = 0;

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

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

This is a cpp file and I got the output in Visual Studio 2010 as

fail
success

Why this behavior? Could you please explain?

Upvotes: 35

Views: 35086

Answers (4)

Mirek
Mirek

Reputation: 1

You could handle such cases if that makes a problem. For the purpose, please activate Code Analysis project property, then a warning is generated:

warning C6319: Use of the comma-operator in a tested expression causes the left argument to be ignored when it has no side-effects.

Upvotes: 0

0s_car
0s_car

Reputation: 11

A better explanation would be the following code interpretation:

if (a,b)
{
    c();
}

Meaning: if, doing operation a, evaluate condition b, if condition b is true, execute function c

Upvotes: 0

jmkuss
jmkuss

Reputation: 146

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.

Upvotes: 3

Yang
Yang

Reputation: 8170

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)

Upvotes: 76

Related Questions