4

According to the table of precedence of operators in C/C++ language (see Wikipedia), the increment operator (++) takes precedence with respect to the assignment operator (=).

Can someone explain why the compiler first assign the value (1 in bill[x]) and then increases the index value (i++) in this simple program. I think it should be the opposite (first increase and then assign):

#include <iostream>
using namespace std;

int bill[] = {16, 17, 18, 19, 20};

int main ()
{
  int i = 3;

  bill[(i++)] = 1; // I think it should be bill[4] = 1;

  cout << bill[0] << endl;
  cout << bill[1] << endl;
  cout << bill[2] << endl;
  cout << bill[3] << endl;
  cout << bill[4] << endl;

  cout << "Index value:" << i << endl;

  return 0;
}

The output is:

16
17
18
1
20
Index value:4

I'm doing something wrong?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Bruno Dermario
  • 123
  • 2
  • 5

4 Answers4

7

i is being incremented, but not before it is used as the array accessor. To get what you're looking for, try `++i' instead. (Prefix instead of postfix.)

ziesemer
  • 27,712
  • 8
  • 86
  • 94
  • You're right, I'm still in doubt: Why the compiler does not do what I'm expecting him to do? But your answer helped solve a problem in my program, using prefix instead suffix to increment. – Bruno Dermario Dec 05 '11 at 04:48
  • Bruno - because some people want the compiler to use the postfix format. Both are useful, and while compilers are great, they do what you tell them to, not what you want them to. :-) – ziesemer Dec 05 '11 at 05:01
4

Another way you can look at this:

bill[(++i)] = 1;

You can read it as, increment 'i' first then do the statement.

bill[(i++)] = 1;

You can read it as, first do the statement then increment 'i'.

If you're wondering how this is possible, internally post-increment can be implemented like this to get the behavior you're seeing:

int post_increment(int &i)
{
  int t = i;
  i = i + 1;
  return t;
}

bill[post_increment(i)] = 1;    // access bill[3] even though i == 4

vs pre-increment which looks like this:

int pre_increment(int &i)
{
  i = i + 1;
  return i;
}

bill[pre_increment(i)] = 1;    // access bill[4] where i == 4
greatwolf
  • 20,287
  • 13
  • 71
  • 105
  • 1
    Excellent answer, your explanation helped me understand how the compiler interprets the precedence operators in source code. Now I see, this language (C/C++) is very powerful and can confuse beginners like me. – Bruno Dermario Dec 05 '11 at 05:15
1

"i++" means, "use as the expression result, the variable value before the increment, but increment the variable".

"++i" means, "increment the variable, and use the incremented value as the result".

Ira Baxter
  • 93,541
  • 22
  • 172
  • 341
1

The increment is being done first. However, i++ increments i and returns a copy of the old value. As others have mentioned, to get the desired behaviour, use ++i, which increments i and returns a reference to i.

voltrevo
  • 9,870
  • 3
  • 28
  • 33