Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the C++ compiler does not give precedence (increment operator under assignment) in this simple program?

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?

like image 711
Bruno Dermario Avatar asked Dec 12 '22 07:12

Bruno Dermario


2 Answers

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.)

like image 80
ziesemer Avatar answered Jan 05 '23 18:01

ziesemer


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
like image 25
greatwolf Avatar answered Jan 05 '23 17:01

greatwolf