Click here to Skip to main content
15,894,343 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Consider following code:

bool Function ( char * str , bool Flag = true )
{
}

This was my intention :
if ( Function ( "blablabla" , false ) )
...

What i inadvertently wrote :

if ( Function ( "blablabla" ) , false )
...

The compiler called Function with Flag = true and forgot my false parameter.

At this point, i would expect an error or warning message of the compiler..
BUT the compiler is happy.
Can anyone explain this ?

Thanks!


What I have tried:

I found the error and fixed it.
BUT i would know why the compiler did not give any error or warning message.
Posted
Updated 4-Feb-22 10:38am

You bumped into the comma operator.
Basically, given an expression a,b,c, ... the compiler evaluates each term, working left to right, discarding the results of all but the leftmost, which is the used as the final value of the expression. Thus, given
C++
if ( f(a), false )
the function call f(a) is made, the result of the call is discarded, the false is used as the condition value of the if expression.
 
Share this answer
 
No, C/C++, comma(,) is treated as an binary operator that evaluates the expression of both sides like && and ||. The behaviour of of comma(,) operator is it evaluated the first expression then second expression evaluated and the value of the second considered as result of whole expression. The comma operator has the lowest precedence of any C operator.
In your case when you called with if(Function("blablabla"), false) first expression which is Function("blablabla") is called with default parameter.
You can read more:
Comma in C and C++ - GeeksforGeeks[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900