IdeaMonk

thoughts, ideas, code and other things...

Wednesday, June 06, 2007

Postfix or Prefix!

Its really interesting to note that for incrementing a variable say j by one, we can simply write j++; instead of j=j+1;
But, hardly do we think of ++j;
Lets see an example :

#include <stdio.h>
int main(void) {
int i,j;
j=2;
i=j++;
printf ("i = j++; makes i = %i and j = %i\n",i,j);
j=2;
i=++j;
printf ("i = ++j; actually makes i = %i and
at same time j = %i\n",i,j);
system("pause"); //tested on win98,xp,2k
return 0;
}

The output would be like-
i = j++; makes i = 2 and j = 3
i = ++j; actually makes i = 3 and at same time j = 3

Now if you try that one out, you will notice that i=++j; actually modifies j first and then puts it in i. So we can conclude that -

In case of i=j++; , the process breaks into -
1. i=j;
2. j++;
In case of i=++j; the following happens -
1. j++;
2. i=j;

Labels:

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home