int i=2;
printf("%d %d",i++,i++);
the output is 3 2
dont care about syntax i executed and got this result can anyone explain the exact reason y it is displayed as 3 2 instead of 2 3
Explain this c program?
the output is right because printf function processes its arguments from right to left..
hence the output for the above code is right
Reply:the maybe is this one:
you declare a variable "i" is equal 2,
and you give output command ("%d %d") which will show a variable of i++, ++i....
i++ means i = i + 1
++i means i = i - 1
and this must be i = 2 + 1 "equal to 3"
then it will memorize that i = 3
and i = 3 - 1 "and precisely 2"
Reply:Looks like the program interprets argument in right-to-left order.
printf(...,...,i++);
printf(...,i++,2);
printf("%d %d",3,2);
I don't sure!
=========
From the above answer:
%26gt; printf("%d %d",i, i++);
It outputs 3 and 2 too.
Reply:It is not 3 2 or 2 3 but it supposed to be 3 3. If you want to be 2 3 then printf("%d %d",i, i++);
Reply:The compiler in C/C++ language will evaluate the function arguments from Right-to-Left !
So be careful that the first argument which has to be evaluated first is the rightmost argument or the last i++ . So here the last i++ means store 2 in function's stack and add 1 to i value ( Now the value of i is 3 !)
In the next step , the first i++ will be evaluated and it means store i value ( or 3 ) in the function's stack and add 1 to i value .
Then printf tries to print the stack values one by one on the screen and because the top of the stack is 3 , the first number appeared will be 3 and similarly the next number will be 2 .
However , if you add another printf("%d",i) to the next line of your code , you will get 4 which is the current value of i .
we have some keywords with relation to this type of compiler reaction like stdcall or PASCAL which are used to specify how the compiler must handle the the parameters and arguments of the function in stack . In C/C++ all of the functions , by default , use stdcall which means Right-to-Left evaluation . PASCAL keyword specifies the reverse order or Left-to-Right evaluation of parameters which follows the exact same way of Pascal language compiler for this situation .
Reply:coz statements in c are executed from top to bottom AND RIGHT TO LEFT
Reply:printf statements execution is from right - to - left..
so the output is 3,2........
++i, i++ both are i+1 only..............
for i-1 it is --i or i-- .
if it is ++i, first it makes i value equal to i+1 and then implements........
if it is i++, after implementing the i value where it used it increments to 1.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment