Connecting Tech Pros Worldwide Forums | Help | Site Map

Can anyone tell me why the output of the following code is as given?

jaffarkazi
Guest
 
Posts: n/a
#1: Jul 3 '08
The code is:

int x = 15;
printf("%d %d\n", (x != 15), (x = 1));
x = 15;
printf("%d %d\n", (x = 1), (x != 15));

The output is:
1 1
1 1

If the , operator goes from right to left, then one of the cases
should give the o/p of (x != 15) as 0.

Regards,
--Jaffar

Willem
Guest
 
Posts: n/a
#2: Jul 3 '08

re: Can anyone tell me why the output of the following code is as given?


jaffarkazi wrote:
) The code is:
)
) int x = 15;
) printf("%d %d\n", (x != 15), (x = 1));
) x = 15;
) printf("%d %d\n", (x = 1), (x != 15));
)
) The output is:
) 1 1
) 1 1
)
) If the , operator goes from right to left, then one of the cases
) should give the o/p of (x != 15) as 0.

There is no , operator in that piece of code.
Just a , separator in the function calls.
That's something completely different.


SaSW, Willem
--
Disclaimer: I am in no way responsible for any of the statements
made in the above text. For all I know I might be
drugged or something..
No I'm not paranoid. You all think I'm paranoid, don't you !
#EOT
Richard Bos
Guest
 
Posts: n/a
#3: Jul 3 '08

re: Can anyone tell me why the output of the following code is as given?


jaffarkazi <jaffar.kazi@gmail.comwrote:
Quote:
printf("%d %d\n", (x != 15), (x = 1));
This causes undefined behaviour. You are assigning to x, and evaluating
x _not_ for the purposes of the assignment, without an intervening
sequence point. Anything may happen; weird numbers is the most likely
outcome, as you observed, but a crash, though unlikely, is possible.
Quote:
printf("%d %d\n", (x = 1), (x != 15));
Quote:
If the , operator goes from right to left,
It does, but there are no , operators in the above statements. The ,
between function call arguments is not the same as the , operator.

Richard
Richard Bos
Guest
 
Posts: n/a
#4: Jul 4 '08

re: Can anyone tell me why the output of the following code is as given?


Martin Ambuhl <mambuhl@earthlink.netwrote:
Quote:
Richard Bos wrote:
Quote:
jaffarkazi <jaffar.kazi@gmail.comwrote:
>
Quote:
Quote:
If the , operator goes from right to left,
It does,
>
Since when?
Erm... since someone reversed the polarity of the neutron flow, so that
left is now right and vice versa...

Richard
Closed Thread