How and why does the output vary for pre and post increment operators?
-
How does the output vary for pre and post increment operators? In this code, how and why does value of 'a' vary? main() { int a=0; printf("%d\n",a++); printf("%d\n",++a); } OUTPUT: 0 2 main() { int a=0; printf("%d %d\n",a++,++a); } OUTPUT: 1,1
-
How does the output vary for pre and post increment operators? In this code, how and why does value of 'a' vary? main() { int a=0; printf("%d\n",a++); printf("%d\n",++a); } OUTPUT: 0 2 main() { int a=0; printf("%d %d\n",a++,++a); } OUTPUT: 1,1
main() { int a=0; printf("%d\n",a++); // POST INCREMENT a is still 0 // HERE a is 1 printf("%d\n",++a); // PRE INCREMENT a is (1+1) = 2 now } main() { int a=0; printf("%d %d\n",a++,++a); // Move from right to left // ++a is pre increment so value for a is 1 for ++a. a++ is post increment so the value still remains 1 for a++ // Here a would be 2 } Preincrement means the value is first operated upon and then used, while in post increment the value is first used then the change happens Hope this helps
Somethings seem HARD to do, until we know how to do them. ;-)_AnShUmAn_
-
How does the output vary for pre and post increment operators? In this code, how and why does value of 'a' vary? main() { int a=0; printf("%d\n",a++); printf("%d\n",++a); } OUTPUT: 0 2 main() { int a=0; printf("%d %d\n",a++,++a); } OUTPUT: 1,1
the developer shouldn't rely on the order of the parameters. your inline printf() (the second example) is really bad. On Visual C++, the parameters are unstacked from right to left, so when you do
printf("%d %d\n",a++,++a)
++a
is evaluated beforea++
. this may be different on other compilers. for how the value ofa
vary, you have to know how pre and post increment operators work. Preincrement (++a) increments the variable and returns its new value (the value after the incrementation). Postincrementation (a++) increments the variable ans returns its old value (the value before the incrementation).[VisualCalc][Binary Guide][CommDialogs] | [Forums Guidelines]