increment and decrement operator in c

Increment and Decrement operators in C

The (++) increment and (–) decrement both operators are unary operators because of both operators operate on a single operand. The increment operator increments the value of any variable by 1 and decrement operator decrements the any variable value by 1. here in the below there are some examples –

++a is Equivalent to a=a+1
–a is Equivalent to a=a-1

These opearators should be used used only with variables. These opearators can not be used with constant and expression here in the below are example we can not use increment and decrement like this–

++9 or ++(a+b+c) are invalids

These opearators are two types
1. prefix increment/decrement
2. postfix increment/decrement

prefix increment/decrement

In the prefix increment or decrement operator is written before the operand(e.g. ++x or –x) here first the value of variable is increment/decrement then the new value is used in any expression or operation. Let take example to understand the concept of prefix

example statement a=++b;
means first the value of variable is increment by one then assign the value of b to the variable a. This statement is equivalent to these two statements

b=b+1;
a=b;

The statement a=- -b; means first decrement the value of b by one then assign the value to a This statement is equivalent to these two statements

b=b-1;
a=b;

Now take the example of prefix increment and prefix decrement.

#include< stdio.h >
void
main()
{
int a=7;
printf(“a=%d\t”,a);
printf(“a=%d\t”,++a); /*prefix increment*/
printf(“a=%d\t”,a);
printf(“a=%d\t”,–a); /*prefix decrement*/
printf(“a=%d\t”,a);
}

Output a=7 a=8 a=8 a=7 a=7

Postfix increment/decrement

Here first the value of variable is used in the operation and then increment or decrement will be perform. Let us take example here x is variable whose value is 5

The statement y=x++; statement means the first the value of x is assign to y then value of x is increase by one. This statement is equivalent to these two statements-

y=x;
x=x+1;

now in this above example value of x is 6 and value of y is 5.as The same the statement y=x–; means first the value of x is assigned to variable y then value of x will decrease by one. This statement is equivalent to these two statements –

y=x;
x=x-1;

Now the value of x will be 4 and y will be 5

#include< stdio.h >
void
main()
{
int x=7;
printf(“x=%d\t”,x);
printf(“x=%d\t”,x);
printf(“x=%d\t”,x–); /*postfix decrement*/
printf(“x=%d\t”,x);
}

output : x=7   x=7    x=8    x=8    x=7