| Author |
Simple boolean question?
|
Dave Johnson
Ranch Hand
Joined: May 25, 2003
Posts: 111
|
|
Here is the code: 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.
|
 |
Ernest Friedman-Hill
author and iconoclast
Marshal
Joined: Jul 08, 2003
Posts: 24057
|
|
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)".
|
[Jess in Action][AskingGoodQuestions]
|
 |
John Smith
Ranch Hand
Joined: Oct 08, 2001
Posts: 2937
|
|
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.
|
 |
Dave Johnson
Ranch Hand
Joined: May 25, 2003
Posts: 111
|
|
|
Many thanks for your time taken to reply, very much appreciated Dave.
|
 |
 |
|
|
subject: Simple boolean question?
|
|
|