#include <iostream>
using namespace std;
int main() {
int num=10;
int *ptr=NULL;
ptr=#
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 :
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=#
(*ptr)++; //no need for assignment to num
(*ptr)++; //no need for assignment to num
cout<<num<<endl;
return 0;
}