You are here:

C/doubt about c

Advertisement


Question
#include<stdio.h>
main()
{
int x=0;
printf("firstincr=%d\nsecondincr=%d\nthirdincr=%d\n",x++,++x,++x);
}

Nemo has some trouble with the above C code.

He expects the output to be:

   First Incr = 1
   Second Incr = 2
   Third Incr = 3

You have to verify if his code prints expected output or not.  Type the code as given above, compile using a C compiler and execute the program.  Write below the output you got:

Answer
Hi Dear Chandu !


Above programme will give the following answer if you execute it in Turbo C/C++ Compiler..

 firstincr = 2
 secondincr = 2
 thirdincr = 1

Is this right ?
answer : Yes it is !!
This is little bit tricky/ difficult to understand ,Lemme summarize some common operator precedence rule before explaining things happening with the above code.
++ operator used in prefix notation possess more priority than the same operator used as suffix.

so with the above case the variable 'x' is arranged in a row as

x++ , ++x , ++x.
Compiler usually executes expression from left to right , while processing the above set of statements from left to right fashion
the first x++ will be ignored ( will be dealt finally since because of low priority to ++ operator in suffix position ) so the last two ++x statements will be executed in a single stretch. now the value of 'x' become 2 (after executing the last two ++x  statements ) and the both value will be pushed to the stack

pass1: ++x;
stack :
1<-Top
++x; ( second ++x )   
stack:
2<-top
2 (old value now turn to 2 , since both refer same memory location)
pass2:
x++; ( Old value of this 'x' alone retained to be 0 , now incremented to 1)
1<-top /* value of x++ after 2 passes */
2      /* value of ++x after two consecutive increments */
2

this s how the argument array of the printf() function will be store as a stack for every printf() request.
again the top element of the argument stack will be tied up with the last argument of the printf() parameters.and so on

now top element 1 is the value of thirdincr
and 2 is the value of secondincr
bottom element 2 is the value of firstincr.

Note: while printing the value assignments for the printf() arguments will be reversed.

Hope the above explanation might have given some ideas about printf() processing;

for more tricky answer please get back to me.
Thanks and Regards
Prince M. Pemnath  

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Prince M. Premnath

Expertise


I'm sure that I can solve any doubts in Turbo C ,Graphics Programing ,Mouse, Hardware Programming ,File System ,Interrupts, BIOS handling , TSR Programming , General Concepts in C Language, handling inline Assembly statements

Experience

Research over 6+ Years

Organizations
CG-VAK Softwares and Exports Limited

Education/Credentials
Masters in Computer Applications

©2012 About.com, a part of The New York Times Company. All rights reserved.