Sunday, May 10, 2009

C C C C C C C C C C C C C C C c?

I'm using a Xp and turbo c++ compiler and now


void main()


{


int i = 1,j = 2;


printf("%d %d");


getch();


}


when i run the above program the output is





2 1


why??

C C C C C C C C C C C C C C C c?
The program invokes undefined behaviour, anything could happen.





My guess is that what is happening in this case is that as both i and j are local variables they are being created on the stack and when printf is called a pointer to the format string is also created on the stack then the printf function is passed a pointer to that entry.





Now printf is a varargs function and it reads the first argument as requiring two further integers, which it is expecting to find on the stack, but (Because they were not created at function call time (but printf has no way to know that)), it pops the first two available arguments off the stack and prints them.





However this is not required behavious and in fact the behaviour may even change from one run to the next.





Regards, Dan.
Reply:Because you're formatting as a double instead of an integer seems the most logical answer. It's been a long time for me and I never liked C but I had Turbo C once.
Reply:ur program shd be like that


void main()


{


int i=1,j=2;


printf("%d %d",j ,i);


getch();


}


then o/p is like that:-


2 1


else in my thinking there shd be no o/p
Reply:This code will print two random integers on the stdout. printf("%d %d",i,j) will print 1 2 and printf("%d %d",j,i) will print 2 1(simply because this is the output you requested!).
Reply:Compiler dependent...
Reply:You need to tell it which variables you want it to print i.e %i or %j
Reply:You should be getting 19.

easter cards

No comments:

Post a Comment