Increment and decrement operator in C

Hello coders! Welcome back!

Today will look at increment and decrement operator in C.
The arithmetic operator is already discussed before (click here to view)

Increment and decrement operator-

The increment operator is used to increment the value of the variable by one. 
The decrement operator is used to decrement the value of the variable by one. 

a++ is nothing but a=a+1. 

Similarly, a-- is nothing but a=a-1.

Here is an important point to remember that both increment and decrement operator is unary operator i.e, it is applied on a single operand. 


There is classification in both increment and decrement operators.

Pre-increment → It first increment the value then assign it to another variable.
example- ++a; 
Post-increment → It first assign the value to another variable then increment the value.
example- a++;
Similarly for decrement operator.

Note that we can't assign the incremented value to the equation neither we can increment an equation. let's look with an example-

It shoots as an error saying lvalue required as increment operator. Let's known what this lvalue means. It means 'left value', the object has an unidentifiable location in the memory. Similarly, there is 'rvalue'.
(a+b)++ is nothing but (a+b)=(a+b) + 1 
Assigning a value to (a+b), which doesn't have the capacity to hold the value. 

Now, let's take an example-



Can you guess the output?? you might think it might produce an error!! but NO, it produces an output. 
Let me explain what is token generation. Before that let's look at what are tokens? 
A token is the smallest element of the program that complier finds it meaningful. Example of tokens are keywords, constants, identifiers, operators, etc. 
Tokens are identified by the lexical analyzer. 
Lexical analyzer scans the source code and finds a meaningful character and then generates a valid token. 
Its first reads 'a' (it forms a meaning full statement). 
then it reads  'a+' (it doesn't form meaningful statement. so it forms a token with 'a')
then it reads'+' (its a valid token i.e, addition operator) 
next, it reads '++' (it is also meaningful operator i.e, increment operator) 
then it reads '+++' (it doesn't form a meaningful statement. so it forms a token with '++')
next, it reads '+' (it is a meaningful statement)
then it reads '+b' (which doesn't have meaning so forms a token with '+')
finally, it reads 'b'.


Recall the definition of post-increment. We are initially using the value of 'a' then perform addition finally increment the value of 'a'.


That's it for this tutorial. Hope so you got a clear idea about increment and decrement operator.
If any doubts drop a comment. Always ready to clear them.

Happy learning!





Comments

Popular post