difference between *b= *b+1 and *b++

Viewed 180

I am trying to change the actual value of a and b in the main function. But when I use *b++ to increment the value of b. It is not working.

#include<iostream>

using namespace std;


int F(int *b,int *c ){
    *b++;
    *c++;

}
int main(){
    int a=1 , b=2;
    cout<<a<<" "<< b<<" ";
    F(&a, &b);

    cout<<a<<" "<< b;
}

but in 2nd Case, the code is working fine.

#include<iostream>

using namespace std;


int F(int *b,int *c ){
    *b = *b+1;
    *c = *c+1;

}
int main(){
    int a=1 , b=2;
    cout<<a<<" "<< b<<" ";
    F(&a, &b);

    cout<<a<<" "<< b;
}

Isn't *b++ and *b=*b+1 same?

2 Answers

They are not the same, the first expression is just manipulating your pointer due to operator precedence.

*b++;     // acts like *(b++)

This increments the pointer, then dereferences it. You need extra parentheses

(*b)++;
Related