Home > database >  Why does this code have different outputs if pointers are incremented differently c
Why does this code have different outputs if pointers are incremented differently c

Time:12-29

#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.

CodePudding user response:

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;
}

CodePudding user response:

(*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.

CodePudding user response:

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

  • Related