Ali Mardan
Ali Mardan

Reputation: 25

Why does this code have different outputs if pointers are incremented differently c++

#include <iostream>
using namespace std;
int main() {
  int num=10;
  int *ptr=NULL;
  ptr=&num;
  num=(*ptr)++; //it should increase to 11
  num=(*ptr)++; //it should increase to 12 but im getting 10
                //if i dont initialize num and just use (*ptr)++ it gives me 11
  cout<<num<<endl;
    return 0;
}

I want to know why is this happening and why am I getting 10 as output.

Upvotes: 0

Views: 89

Answers (3)

user12002570
user12002570

Reputation: 1

why is this happening

Because you are using post-increment operator instead of pre-increment operator.

Replace (*ptr)++ with:

num = ++(*ptr);//uses pre-increment operator

And you will get 12 as output at the end of the program which can be seen here.

Alternative solution

You can also just write (*ptr)++; without doing assignment to num. So in this case code would look like:

int main() {
  int num=10;
  int *ptr=NULL;
  ptr=&num;
  (*ptr)++; //no need for assignment to num
  (*ptr)++; //no need for assignment to num
                
  cout<<num<<endl;
    return 0;
}

Upvotes: 1

Peter Trencansky
Peter Trencansky

Reputation: 373

It is caused by assigning to num. ++ operator returns old value and then increments. However, then the old value is assigned to num.

Upvotes: 1

user16004728
user16004728

Reputation:

(*ptr)++ increases num to 11 but returns its previous value (10), because the ++ is postfix.

So with num = (*ptr)++, you are temporarily increasing num to 11, but then (re)assigning it with 10.

Upvotes: 4

Related Questions