c++ - comma operator in if condition -


int = 1, b = 0;  if(a, b)    printf("success\n"); else    printf("fail\n");  if(b, a)    printf("success\n"); else    printf("fail"); 

this cpp file , got output in visual studio 2010

fail success 

why behavior? please explain?

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

in c , c++ programming languages, comma operator (represented token ,) binary operator evaluates first operand , discards result, , evaluates second operand , returns value (and type).

in first if:

if (a, b) 

a evaluated first , discarded, b evaluated second , returned 0. condition false.

in second if:

if (b, a) 

b evaluated first , discarded, a evaluated second , returned 1. condition true.

if there more 2 operands, last expression returned.

if want both conditions true, should use && operator:

if (a && b) 

Comments

Popular posts from this blog

linux - xterm copying to CLIPBOARD using copy-selection causes automatic updating of CLIPBOARD upon mouse selection -

c++ - qgraphicsview horizontal scrolling always has a vertical delta -