-3

This may already be a question out there, but with the lack of specific key terms, it's a bit hard to search for. Just looking for more insight on this topic.

Right now, I'm working in C++ and wondering why my value is replaced with an incremented value when I compare using "++".

So here, we print 14 times (numbers 1-14).

int i = 0, x = 0;
while (x < 30) {
    x++;
    if (13 < i++) break;
    cout << i << endl;
}

Here, we print 30 zeros.

int i = 0, x = 0;
while (x < 30) {
    x++;
    if (13 < i+1) break;
    cout << i << endl;
}

And this just plain doesn't work. (I wanted to try because i++ = i=i+1).

int i = 0, x = 0;
while (x < 30) {
    x++;
    if (13 < i=i+1) break;
    cout << i << endl;
}
Bella
  • 39
  • 2

2 Answers2

3

Expression i++ has both a value and a side effect. The value is that of i, and the side effect is that i is incremented (after having taken its value as expression result).

Expression i+1, in contrast, does not have a side effect, it only has a value (which is the value of i plus 1) but leaves the value of i as it is.

That's why.

Stephan Lechner
  • 34,891
  • 4
  • 35
  • 58
1

And this just plain doesn't work. (I wanted to try because i++ = i=i+1).

The reason it doesn't work is because of operator precedence in this expression:

 if (13 < i=i+1) break;

It is evaluated by compiler as

if ((13 < i)=(i+1)) break;

and assignment to bool fails. What you need is to add correct parentheses for it to work:

int i = 0, x = 0;
while (x < 30) {
    x++;
    if (13 < (i=i+1)) break;
    cout << i << endl;
}

https://ideone.com/0NSNwU

1
2
3
4
5
6
7
8
9
10
11
12
13
Killzone Kid
  • 6,171
  • 3
  • 17
  • 37