Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading