Constellation
Constellation

Reputation: 65

How is the increment operator evaluated in C programs?

I have two expressions:

int a=5; 
int c=++a;// c=6, a=6
int b=a++;// b=6, a=7

In the second instruction, the increment is evaluated first and in the third instruction, the increment is evaluated after the assignment.

I know that the increment operator has a higher priority. Can anyone explain to me why it's evaluated after assignment in the third expression?

Upvotes: 0

Views: 520

Answers (2)

CherryDT
CherryDT

Reputation: 29062

++a and a++ are simply different operators, despite the same symbol ++. One is prefix-increment, one is postfix-increment. This has nothing to do with priority compared to assignment. (just like a - b and -a are different operators despite the same symbol -.)

EDIT: It was pointed out that this is about C and not C++... oops. So, the following explanation may be confusing if you only know C; all you need to know is that int& is a reference to an int, so it's like having a pointer but without the need to dereference it, so modifying a inside of these functions actually modifies the variable you passed into the functions.

You could imagine them like functions:

int prefixIncrement(int& a) {
  return ++a;
}

...is the same as:

int prefixIncrement(int& a) {
  a += 1;
  return a;
}

And:

int postfixIncrement(int& a) {
  return a++;
}

...is the same as:

int postfixIncrement(int& a) {
  int old = a;
  a += 1;
  return old;
}

For nitpickers: Yes, actually we'd need move semantics on the return value for postfixIncrement.

Upvotes: 0

dbush
dbush

Reputation: 225294

The result is not related to the order of operations but to the definition of prefix ++ and postfix ++.

The expression ++a evaluates to the incremented value of a. In contrast, the expression a++ evaluates to the current value of a, and a is incremented as a side effect.

Section 6.5.2.4p2 of the C standard says the following about postfix ++:

The result of the postfix ++ operator is the value of the operand. As a side effect, the value of the operand object is incremented (that is, the value 1 of the appropriate type is added to it).

And section 6.5.3.1p2 says the following about prefix ++:

The value of the operand of the prefix ++ operator is incremented. The result is the new value of the operand after incrementation. The expression ++E is equivalent to (E+=1)

Upvotes: 5

Related Questions