0

I have code:

#include <bits/stdc++.h>

int main()
{
    int b = 5;
    int * a = &b;
    *a++;
    std::cout << *a;
}

Why pre-incremental works well, but post not working?

  • The `*a++;` is as if you did `*a; ++a;`. – Eljay May 26 '23 at 12:29
  • 3
    [C++ operator precedence](https://en.cppreference.com/w/cpp/language/operator_precedence) - post-increment has higher precedence than dereference, so it's `*(a++);` – Yksisarvinen May 26 '23 at 12:30
  • oh ok, i got it – Rostik Romanets May 26 '23 at 12:31
  • [Why should I not #include ?](https://stackoverflow.com/questions/31816095/why-should-i-not-include-bits-stdc-h) – Jesper Juhl May 26 '23 at 12:45
  • Using pre-incrementation, there is no ambiguity `++*a` increment the pointed, `*++a` increment the pointer. But with post-incrementation parentheses may be needed: `(*a)++`the pointed is incremented, `*a++` or `*(a++)` the pointer is incremented. – dalfaB May 26 '23 at 12:56
  • `std::cout << *a;` is UB because a no longer points to b. Could point to anything. – doug May 26 '23 at 17:37

0 Answers0