-1
int n = 1;
n = n++;
cout<<n<<endl;

output:1

I have searched it on Google. Analysis says that "n = n++" is:First assign n to n, then n add 1.

I don't know why it is giving output as 1, rather than 2.

Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110
lyzMaster
  • 530
  • 1
  • 6
  • 17
  • 4
    The code suggests C++ but you also have tags for Java and C. It matters which one it is. So which is it? – dbush May 03 '18 at 03:56
  • 3
    I have removed the Java and C tags, because this code snippet is clearly C++. – Dawood ibn Kareem May 03 '18 at 04:01
  • A possible expansion is `int tmp = n; n++; n = tmp;` which yields 1. However, as others have commented, the expansion is ambiguous, since it could have been `int tmp = n; n = tmp; n++; ` which would have yielded what you wanted to see. Either expansion is possible, which is why it's best not to write such ambiguous code. – Stephen Quan May 03 '18 at 04:11
  • 1
    Definitely C++. In C++: `n += 1;`, ‘n++;` and `++n` all increment `n` by one. I think that’s what you’re trying to do. Work on your question quality! – bcr May 03 '18 at 04:37

1 Answers1

2

This code is undefined behavior. The compiler can do anything, even make demons fly out of your nose if it feels like it. To find out more about this, you can read up at https://en.wikipedia.org/wiki/Sequence_point

N00byEdge
  • 1,106
  • 7
  • 18