opertor ++

R

ravinder thakur

hello guys,

I am apparently puzzled by a very simple piece of code. What should be
the value of x after this statement ?

int x = 10;
x = x++;

I expect the value to be 10(since this is postfix). However the value
turns out to be 11. Any idea whats happening ?

Thanks
xoxo
 
R

red floyd

hello guys,

I am apparently puzzled by a very simple piece of code. What should be
the value of x after this statement ?

int x = 10;
x = x++;

I expect the value to be 10(since this is postfix). However the value
turns out to be 11. Any idea whats happening ?

The behavior is undefined.
 
S

Senggen Choi

hello guys,

I am apparently puzzled by a very simple piece of code. What should be
the value of x after this statement ?

int x = 10;
x = x++;

I expect the value to be 10(since this is postfix). However the value
turns out to be 11. Any idea whats happening ?

Thanks
xoxo

You need another variable.

int y = x++;

then y should be 10 as you expected, and x equals 11.
 
G

Guest

I am apparently puzzled by a very simple piece of code. What should be
the value of x after this statement ?

int x = 10;
x = x++;

I expect the value to be 10(since this is postfix). However the value
turns out to be 11. Any idea whats happening ?

from the C FAQ
http://c-faq.com/
(and this is the same in C++)

FAQ 3.1 "Why doesn't this code: a = i++; work?"
 
H

Helfer Thomas

Your example is funny since different compilers give different results:
- g++ gives 11
- clang gives 10

However I can't tell you what the results shall be according to the
standard (du to the assignement I would expect 11...)

Sincerly,

Helfer Thomas


Le 17/05/2012 07:20, ravinder thakur a écrit :
 
J

Juha Nieminen

Helfer Thomas said:
Your example is funny since different compilers give different results:
- g++ gives 11
- clang gives 10

Both are correct. (In fact, if they produced -7 and 50391, they would
have still been correct.)
However I can't tell you what the results shall be according to the
standard (du to the assignement I would expect 11...)

It's undefined behavior, so anything goes.
 
J

Jorgen Grahn

Le 17/05/2012 07:20, ravinder thakur a écrit :
Your example is funny since different compilers give different results:
- g++ gives 11
- clang gives 10

However I can't tell you what the results shall be according to the
standard (du to the assignement I would expect 11...)

gcc gives a warning "operation on 'x' may be undefined". That should
be a quite clear indication about what result you can expect, right?

Never run your compiler without enabling full warnings.

/Jorgen
 

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

Staff online

Members online

Forum statistics

Threads
473,767
Messages
2,569,570
Members
45,045
Latest member
DRCM

Latest Threads

Top