Ask your own question, for FREE!
Computer Science 6 Online
OpenStudy (yrelhan4):

ok i am just a beginner in c.. i have the following prog. #include int main(){ int x,y,z; x=y=z=1; z = ++x || ++y && ++z; printf("x=%d y=%d z=%d\n",x,y,z); return 0; } the output is 2,1,1 why is x being incremented at all? i mean the increment of x,y,z is for evaluation of z only, isnt it? shouldnt the output be 1,1,1? because we already defined the values of x and y, and later calculated z?

OpenStudy (yrelhan4):

@ganeshie8

OpenStudy (e.mccormick):

Look at your order of operations/evaluations/precedence. In what order is this evaluated? z = ++x || ++y && ++z; This is from Microsoft, but it is basically the same for any C you will run into. http://msdn.microsoft.com/en-us/library/2bxt6kc4.aspx

OpenStudy (yrelhan4):

The and operator is evaluated first, and then the or operator. Yeah?

OpenStudy (e.mccormick):

And the ++ fires before both of them, but when it comes to the and/or, they are left to right. So because ++x is true, the other side is NEVER evaluated.

OpenStudy (e.mccormick):

z = ++x || ++y && ++z; goes into the program as: z = OK, we will assign something to z. ++x Increment this! x || That is true, stop evaluating the right. Therefore: z = (incremented)x Should be all it does.

OpenStudy (e.mccormick):

And yes, by that logic, it should be 212. Not sure why it is 211.

OpenStudy (yrelhan4):

Thank you so much. I get it. And i think i know the answer to that part. We are using logical operators here to evaluate z. So the answer can only be 0 or 1(false or true). As 2 || anything is always true.. so we get 1 for z.

OpenStudy (e.mccormick):

DOH! Yah, I forgot that. LOL.

OpenStudy (e.mccormick):

Which is why many programmers do increments on separate lines. It makes things cleaner. There, that fixed it.

OpenStudy (yrelhan4):

We have tests having questions like these. And i am like, man i can write this in a better way. But yeah, it kinda improves the logic. Thank you again. :)

OpenStudy (e.mccormick):

Yes, usually the point is to see the twisted order of how C does things. I think those tests are why many programmers do some things on separate lines!

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!