Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
180 views
in Technique[技术] by (71.8m points)

c++ - comma operator in if condition

int a = 1, b = 0;

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

if(b, a)
   printf("success
");
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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...