Postfix & Prefix Operators

Unary operators
(Those operators which work on one variable) 
++    --

The prefix and postfix forms of ++ is:
++a  and a++

Similarly, those of -- is:
--a and a--

As the name suggests,
Postfix operators take effect after the line is executed. (a++)
Prefix operators take effect before the line is executed. (++a)

This concept is pretty easy but for those who still haven't understood,
the following examples should be sufficient.

EXAMPLES:

 
int a=10;
cout<<a++;

Output:
10 

 
int a=10;
cout<<++a;


Output:
11

 
int a=10;
cout<<a++<<'\n';
cout<<a<<'\n';
cout<<++a<<'\n';


Output:
10
11
12 

 
int a=10;
cout<<++a<<'\n';
cout<<a<<'\n';
cout<<a++<<'\n';
cout<<a<<'\n';


Output:
11
11
11
12

 
int a=10;
cout<<a--<<'\n';
cout<<--a;

Output:
10 
8


 
int a=10;
cout<<a+++++a;

//(a++) + (++a)
// (10) + [(11)+1]
//(10) + (12)



Output:

22

*SAME FOR
++a + a++
(reason: 11+11)


//Assuming there is a function

int add(int,int);
which adds the two called integers.


int a=10; 
int b=5;
int sum=0;

sum=add(a++,--b);
// a --> 10 (postfix)
// b --> 4 (prefix)

cout<<"Sum="<<sum;
cout<<"\n A="<<a;
cout<<"\n B="<<b;




Output:

Sum=14
A=11
B=4





BUT... There is a common misunderstanding
which many of us tend to make:

The postfix and prefix operators only are valid when the output
is required spontaneously at that instant. 
(like in cout sttments or function calls)


AFTER THE SEMICOLON,

 THE PREFIX AND POSTFIX OPERATOR ARE THE SAME.

If its confusing, just think of the for loop.

for(int i=0; i<n; i++)

and

for(int i=0; i<n; ++i)

BOTH OF THEM PERFORM THE SAME TASK. 
THERE IS NO DIFFERENCE.

MORE EXAMPLES:



int a=10;
a++;
//or a=a++;
cout<<a;


Output:
11


int a=10;
++a;
cout<<a;


Output:
11


int a=10;
--a; a++; 
cout<<a;


Output:
10
















END OF REQUIRED SECTION
(BOTTOM IS ADVANCED EXPERIMENTING)



TO CLARIFY FEW TOUGHER CONCEPTS
WHICH I DOUBT WILL COME IN THE EXAMS.

i.e. Don't Confuse yourself if you're unsure.

(1)

a++; SAME AS ++a; SAME AS a=a++; SAME AS a=a+1;

 
int i=10;
int j=10;

i=i++;
j++;

cout<<"i="<<i;
cout<<"\n j="<<j;


Output:
 11 
11


(2)

IF s=a++; and a=a++; (or a++;)
s NOT EQUAL TO a


  int p=10, q=10;

  int s=p++;
  q=q++;

  cout<<s;
  cout<<'\n'<<q;


Output:
10
11



(3)



int a=10,b=10;


      a=++a + a++;
 int s=++b + b++;

 cout<<a<<endl;
 cout<<s<<endl;

 a=10; b=10;
 cout<<(++a + a++);


OUTPUT:

23
22
22


Comments