c++ unary increment operator

M

MSDousti

Hi,
I'm confused with C++'s unary increment operator(++).
Consider the following code:

//////////////////////////////////////////////////////////////////////
#include <iostream>
using namespace std;

int main()
{
int a=2;
a= (a==2 ? a+=100:0) + (a>3 ? a+=200:1000) + a++;
cout << a << endl;
return 0;
}
//////////////////////////////////////////////////////////////////////

I have run this code both on linux (using g++) and windows (VS.NET).
Surprisingly, the resaults were incompatible!
g++ answers: 507
VS answers: 707

Can anyone help?
 
M

Mike Wahler

MSDousti said:
Hi,
I'm confused with C++'s unary increment operator(++).
Consider the following code:

//////////////////////////////////////////////////////////////////////
#include <iostream>
using namespace std;

int main()
{
int a=2;
a= (a==2 ? a+=100:0) + (a>3 ? a+=200:1000) + a++;
cout << a << endl;
return 0;
}
//////////////////////////////////////////////////////////////////////

I have run this code both on linux (using g++) and windows (VS.NET).
Surprisingly, the resaults were incompatible!
g++ answers: 507
VS answers: 707

The language does not specify the order in which the
expressions:

(a==2 ? a+=100:0)
(a>3 ? a+=200:1000)
a++

.... are evaluated.
Can anyone help?

Break the code down to where you have sufficient control
over evaluation order. Look up 'sequence points'. I can't
tell you what you need here, since you don't say which result
you want.

-Mike
 

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

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top