-5

I was experimenting with some code when I discovered something odd. I had the following code:

#include <iostream>

int add_one_return(int a) {
    return a++;
}
void add_one_ref(int &a) {
    a++;
}

int main(int argc, char const *argv[]) {
    int a1 = 5;
    int a2 = 5;
    a1 = add_one_return(a1);
    add_one_ref(a2);
    std::cout << a1 << " " << a2 << std::endl;
    return 0;
}

But when I ran it the program printed 5 6. I went back and changed add_one_return to:

int add_one_return(int a) {
    return ++a;
}

and it worked! Why does ++a work but not a++? Is there ever an advantage to a++, because I also hear that in a for loop you want to use for(int i = 0; i < someVar; ++i) {}, so why a++ at all?

Axel Persinger
  • 331
  • 2
  • 14
  • Naturally, the two results are different. Essentially, `add_one_return` is equivalent to `int add_one_return(int a) { return a; }` because post-increment of `a` is ignored. – Sergey Kalinichenko Dec 26 '17 at 19:13
  • There are two questions here. "Why do they give different results" is easily answered by the duplicate as "because they are different operators". The other question is more interesting: "when do you need the post-increment form". The duplicate doesn't really address that. – Brent Bradburn Dec 26 '17 at 19:24
  • Look at `C++ preincrement and postincrement`, you will find out the difference and what you want to use where. – ProXicT Dec 26 '17 at 19:56

1 Answers1

4
  • a++ returns what a was before, and then increments it, so originally your function would just return the argument and then add one.

  • ++a increments the variable and then returns, which is what you want here.

Tom de Geus
  • 5,625
  • 2
  • 33
  • 77
mrFoobles
  • 149
  • 2
  • 9