Thursday, July 30, 2009

Need Immediate solution; What is the output of the following C++ program?

What is the real output of the following program?





#include%26lt;iostream.h%26gt;


#include%26lt;conio.h%26gt;





int main()


{


int n=10;


clrscr();


cout%26lt;%26lt;n%26lt;%26lt;"\t"%26lt;%26lt;++n%26lt;%26lt;"\t"%26lt;%26lt;n++%26lt;%26lt;"\t"%26lt;%26lt;...


getch();


return 0;


}





It is a question asked in our exam.





It shows 11 11 9 10


on turbo C++


and 10 11 11 12


on Dev C++..





Does this program work on Visual C++?


If yes please give me its output.





I need the real output.

Need Immediate solution; What is the output of the following C++ program?
This is what the C++ Standard calls undefined behavior. The compiler has the freedom to order the parameter expressions in a single statement as it chooses. As you have seen, different compilers make different selections.





In short, this is a bad program. There is no "real" output.





To make it work correctly, you need to break the one long statement into many smaller statements. By using multiple statements, you force all the side effects of the previous statement to be completed before going to the next. For example:





cout %26lt;%26lt; n %26lt;%26lt; "\t";


cout %26lt;%26lt; ++n %26lt;%26lt; "\t";


cout %26lt;%26lt; n++ %26lt;%26lt; "\t";


// etc.





YA clipped your line, but done this way, the first three items would be:


10 11 11;
Reply:the program is a console application (It doesn't have a user interface like windows programs, since it operates in DOS), so it cant be called a visual C++ program, though it would work if you made a console application in VC++.


On yahoo answers, the line where you've given a cout command is incomplere, so i can't tell you its exact output, but if you end the cout line at





cout%26lt;%26lt;n%26lt;%26lt;"\t"%26lt;%26lt;++n%26lt;%26lt;"\t"%26lt;%26lt;n++;





the output is 12 12 10


No comments:

Post a Comment