2

Why is it that when I use *a++ it doesn't affect my answer and gives me a warning. However it works fine with *a=*a+1 in the below code?

#include <bits/stdc++.h>
using namespace std;

void incrementptr(int* a)
{
    //*a++;
    *a=*a+1;
}

int main()
{
    int a=10;
    cout<<a<<endl;
    // increment(a);
    // cout<<a<<endl;

    incrementptr(&a);
    cout<<a<<endl;
    
    return 0;
}
y_159
  • 458
  • 3
  • 15
  • 12
    `*a++` is `*(a++)`, not `(*a)++`. – HolyBlackCat Aug 20 '21 at 08:38
  • Or perhaps this: [Pointer Arithmetic: ++*ptr or *ptr++?](https://stackoverflow.com/questions/5209602/pointer-arithmetic-ptr-or-ptr) – WhozCraig Aug 20 '21 at 08:42
  • please post the code the question is about, not the working code. Details do matter and it can cause confusion and misunderstanding when the code you are asking about is the one behind comments – 463035818_is_not_an_ai Aug 20 '21 at 08:46
  • *it doesn't affect my answer*?. Try to run your program multiple times and you will see different values of a for `*a++`. – y_159 Aug 20 '21 at 08:46

2 Answers2

8

operator precedence: postfix ++ has higher precedence than *, hence *a++ is parsed as *(a++). It increments the pointer and dereferences a (the value before the increment) and the result of the expression is unused.


I suppose this is just to practice pointers, but there shouldn't be any pointer in your code. Only use pointers as argument, when a nullptr is a valid input to the function. Otherwise pass a reference (and use preincrement when you don't need the value before the increment, it won't make a difference for an int, but in general post can be more expensive than pre):

void increment(int& a) { ++a; }
463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
  • 1
    Oh, it seems that I was the one making the mistake. According to [§7.2.1.5 of the ISO C++20 standard](https://timsong-cpp.github.io/cppwp/n4861/expr.post.incr), the value computation of the ++ expression is sequenced before the modification of the operand object. Therefore, your previous formulation was actually correct. Sorry about that. – Andreas Wenzel Aug 20 '21 at 10:02
2

The ++ operator has preference over the * operator so when you are doing *a++ it first increments the pointer and then reaches its value. If you want to increment the value of *a you can do it with (*a)++.

Here you have the preference table: https://en.cppreference.com/w/cpp/language/operator_precedence