I dont understand this syntax

A

abubakarm

Hi,

I accidentally wrote this:

if (1, 2);

and it compiles fine. I want to know why is it correct and what does
it mean in c++. The compiler i'm using in visual C++ 2k5.

Regards,

...ab
 
I

Ivan Vecerina

: Hi,
:
: I accidentally wrote this:
:
: if (1, 2);

Except when given a different meaning by context (for
instance to separate function parameters, or initializers),
a "," in C and C++ is interpreted as a comma operator:
This operator first evaluates the left hand side expression,
then evaluates the right hand side expression. The result
is the right hand side expression.

if( 1, 2 ) -> condition will always pass (value is 2 -> true)
if( 0, 1 ) -> condition will always pass (value is 1)
if( 0, 0 ) -> condition will always fail (value is 0)

To experiment with this, you may write:
cout << ( 1, 2 ); // prints 2
cout << ( 99, "HELLO" ); // prints HELLO
cout << ( 1, 4, "TEST", 3 ); // prints 3
etc

: and it compiles fine. I want to know why is it correct and what does
: it mean in c++. The compiler i'm using in visual C++ 2k5.
The behavior you observed was correct.

Hope this helps -Ivan
 
R

Rahul

Hi,

I accidentally wrote this:

if (1, 2);

and it compiles fine. I want to know why is it correct and what does
it mean in c++. The compiler i'm using in visual C++ 2k5.

Regards,

..ab

, is evaluated left to right and the last value is considered.

if (1,2,3) etc...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top