Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between &++x and &x++

Although this question might be answered somewhere and I could not find it.

Below written first statement work whereas second does not? WHY?

int main() {
  int x = 1, y = 2;

  int *p = &++x; // First
  std::cout << "*p = " << *p << std::endl;

  // int *q = &x++; // Second
  // std::cout << "*q = " << *p << std::endl;
}
like image 554
Hemant Bhargava Avatar asked Apr 08 '20 19:04

Hemant Bhargava


1 Answers

In this declaration

int *p = &++x;

there are used two unary operators: pre-increment ++ and taking of address. Unary operators are executed from right to left. So at first the variable x is incremented and its address is assigned to the pointer p, The result of the pre-increment operator is lvalue of the incremented object.

So for example such an expression like this

++++x;

is correct.

In this declaration

int *p = &x++;

there are used the postfix operator post-increment ++ and the unary operator of taking address. Postfix operators have a higher priority relative to unary operators. SO at first the post-increment is executed. Its result is a temporary object that has the value of the variable x before incrementing. Then the operator of taking of address is executed.

However you may not take an address of a temporary object. So for this declaration the compiler will issue an error.

Opposite to the pre-increment operator such an expression like this

x++++;

is invalid.

From the C++ 17 Standard (5.3.2 Increment and decrement)

1 The operand of prefix ++ is modified by adding 1, or set to true if it is bool (this use is deprecated). The operand shall be a modifiable lvalue. The type of the operand shall be an arithmetic type or a pointer to a completely-defined object type. The result is the updated operand; it is an lvalue, and it is a bit-field if the operand is a bit-field....

And (5.2.6 Increment and decrement)

1 The value of a postfix ++ expression is the value of its operand. [ Note: the value obtained is a copy of the original value — end note ]...

In C the both operations yield a value. So in C you also may not write

++++x;
like image 97
Vlad from Moscow Avatar answered Nov 04 '22 12:11

Vlad from Moscow