Now I know that if the if statement read: if(a==true), the code would then compile & run & display Goodbye. What I cannot understand is why as the code stands does it take a boolean value as false and then interprete it as true? I have seen this a few times and although I know to answer it correctly I still don't understand why the code does what it does! Thanks, Dave.
The value of the assignment expression "a = true" is true -- it assigns "true" to "a" and returns the value "true". So it's as if you had written "if (true)". The fact that assignment expressions have a value is what makes it possible to write statements like "i = j = k = 0;" which is interpreted as "i = (j = (k = 0));" There's a really easy way to avoid this error, by the way: you should never compare to a boolean literal. Instead of writing "if (a == true)", always write "if (a)" . Similarly, you can and should replace "if (a != true)" with "if (!a)".
What I cannot understand is why as the code stands does it take a boolean value as false and then interprete it as true? Within your "if", you have an expression that assigns true to the variable. Since the variable is of boolean type, the whole expression then evaluates to true.
Joined: May 25, 2003
Many thanks for your time taken to reply, very much appreciated Dave.