Increment and Decrement Operators in C/C++
I found the sign '++
and — — '
confusing for many beginners
, So let’s explain what’s actually they mean,
I will discuss Pre and Post Increment.
Let’s initialize x to an integer value, 10.
Now make another variable y, and put ++ before x:
As we know, pre means before, ++ stands before the integer 10. This is called pre-increment, we are pre -incrementing the value of y. So what I mean is 10 plus 1, and that’s 11. So, if we print y we will get 11, (10+1).
Now y hold’s 11.
Now if we just change pre-increment operator to -- then :
int y = --x // 10 - 1 --> 9
then the same process
will happen, I will leave this for you. Try it out!
Let’s initialize x to an integer value, 10. And I will do the same steps just put ++ after the 10.
You may be shocked to see the result of y is unchanged…now, print y :
/* result of y */
10 //no worrry! see below
Why did this happen? Well, This is the post-increment rule. Post means after, so what x ++ did was not adding 1 to 10 for now. Let’s print the value of x now.
As you see, we did a post-increment on x ( y = x++), this means you don’t want to add 1 directly to x and also don’t want y to hold the incremented of the value of x. Instead, we want to add 1 after this expression int y = x++ evaluated, this is called post-increment. We don’t want to store the incremented value of x into y, instead, our want is just to leave this expression like,
int y = x++ --> int y = x + 0, so y = x then x = x+1.
So here, the increment is done after the evaluation of the expression(int y = x++). And we just call this a Post-Increment. This how it works,
Note that, The main point is that ++x increments the value and immediately returns it. But, x++ do the opposite as it doesn't return the incremented value immediately.
Now, let’s mix these two, and see what’s happening!
++ and — — Mixed,
Let’s try this code
int x = 10
int y = 20
int z = ++x + y++
Now, simply if we print z we will get :
Let me tell you first, Pre Increment always gets executed first, so ++x means (10+1 →11) and y++ ( think like 20 + 0 → 20) and the result is (11+20 → 31). COOL...
Now try this one below:
int x = 10
int z = ++x + x++
Careful !, here the pre-increment does its job first and so ++x is pre-incremented first! , so now x is (10+1 → 11) Right? now after the pre-increment, the post-increment begins, its job is easy now, and that’s:
x++ → 11+ 0 = 11
So now both ++x and x++ added together and we got the result :
That’s Simple and Easily gets done, I hope I am able to help you. Let me know in the response section.
Subscribe to get your daily round-up of top tech stories!