why does this compile (c++)

TecHNooB

Diamond Member
Sep 10, 2005
7,458
1
76
if(function(a),false)
{
}

I made a boo boo and wrote that instead of

if(function(a, false))
{
}

I've done this a few times actually :|
 

Cogman

Lifer
Sep 19, 2000
10,286
147
106
Whatever function you are using has been overloaded as

type function(type a, bool b)

and

type function(type a)
 

Merad

Platinum Member
May 31, 2010
2,586
19
81
The comma is an operator. You basically wrote

if(operator,(function(a), false))

I'm a little rusty but IIRC it typically returns the first argument unless it's been overridden to do something else.
 

mv2devnull

Golden Member
Apr 13, 2010
1,539
169
106
Code:
for ( a=b=0; a<9; ++a, b+=5 ) ...
Okay, not the only way to iterate now, but it probably was quite expressive earlier.
 

Markbnj

Elite Member <br>Moderator Emeritus
Moderator
Sep 16, 2005
15,682
14
81
www.markbetz.net
The strict answer is that when the compiler sees...

if (expr) { }

... it evaluates expr to see if it is true, and if it is enters the conditional block of code. Your expression...

(function(a),false)

... is perfectly legal. The comma operator is used in C++ to separate expressions, so these two expressions are evaluated in order of precedence, i.e. left to right. Therefore the effect of the combined expression will be to, in order:

a) execute the function, passing a, and discarding the return value
b) return false to the if operator