-2

I have the following c++ program:

#include <iostream>
using namespace std;
//looping through arrays backwards
int main() {
    int a[3] {1, 2, 3};
    int x = sizeof(a), y = sizeof(int), z = x / y;
    for(int i = z - 1; i >= 0; i--) {
        cout << a[i] << " ";
    }
    return 0;
}

And it outputs 3 2 1. But if I change the first parameter in the for loop to int i = z--;, it outpus 2 3 2 1 and I don't understand why. Aren't z - 1 and z-- supposed to be the same thing? Could someone please explain why? Also, I'm a begginer in C++ and I'm learning via the W3Schools tutorial about it. Thanks!

  • `z--` returns the value _before_ it's changed. You want `--z`, which returns the new value. – ChrisMM Jul 03 '22 at 21:50
  • `z--` is a post decrement. The value is decremented but the returned value is the original value. Use `--z` if you want to decrement the value and have the new value returned. – Retired Ninja Jul 03 '22 at 21:50
  • 2
    Are you talking about the "tutorial" [here](https://www.w3schools.com/cpp/cpp_operators.asp)? If so, yes it is clear why you are confused. That doesn't explain anything properly. I recommend you to drop this tutorial and use e.g. one of the [recommended books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) instead. – user17732522 Jul 03 '22 at 21:52

1 Answers1

1

The expression z-- evaluates to z, then - as a side effect - z is decremented (scheduled according to scheduling rules). This means, you're essentially saying int i = z in your loop (and then decrement z, but it's not used anymore) - therefore, your code has UB. The 2 printed is purely coincidental, anything might be printed or anything could happen in your code. If you'd like to use --, use it as prefix, i. e., int i = --z.

lorro
  • 10,687
  • 23
  • 36