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

2
  • 1
    Yet another evidence of why it is not good to change a value twice in a single expression. :-) Commented Dec 29, 2021 at 9:30
  • 1
    Just a note that, before C++17, num=(*ptr)++; exhibits undefined behaviour. Compilers will likely not spot it but, replacing with num = num++ will generate warning : multiple unsequenced modifications to 'num' [-Wunsequenced] with clang-cl (using the C++14 Standard). Commented Dec 29, 2021 at 9:32

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

1 Comment

New to coding and don't know the term post fix i'll search it up thanks for reply
1

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

Comments

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

3 Comments

Or just (*ptr)++; for each statement.
im rather new and didn't knew that post and pre increment or decrement can affect a code like this thanks for reply tho
@AliMardan You're welcome. Also note that as Adrian suggested you can also use (*ptr)++; without assigning to num. I have added this at the end of my answer. Check it out.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.