tag:blogger.com,1999:blog-28172905.post5886679960058880241..comments2024-03-03T17:53:46.947-05:00Comments on (x, why?): (x, why?) Mini: Boolean(x, why?)http://www.blogger.com/profile/17499160002806879025noreply@blogger.comBlogger1125tag:blogger.com,1999:blog-28172905.post-92041539512056737752015-07-20T17:45:25.571-04:002015-07-20T17:45:25.571-04:00First off, I'm not really a programmer either ...First off, I'm not really a programmer either but I keep doing it here and there and here are my thoughts about what you call clever programming:<br /><br />- In a strictly typed language where your x is Boolean and can hence only be true or false, it is accepted and in fact very common to write "if x then" instead of "if x == true then".<br /><br />- Yet this is done for brevity/legibility, in any compiled language there is zero difference in speed (the compiler takes care of optimizing needless things away anyways).<br /><br />- The trouble starts in a loosely typed language where x is not declared and hence has no fixed type, so it could be assigned to a Boolean, an integer, a string, or even an object. Here, if you write "if x then" it might not always do what you thought. The if will try to cast x into a Boolean applying a rule similar to the one you mentioned (0 means false, \neq 0 means true). A typical example where this goes wrong is when x is the result of a function call. A function might for instance return an integer if things go well but in the rare case something goes wrong it returns a Boolean "false". Now you actually need to check whether x is false or whether it is zero because zero might mean success. Loosely typed languages usually allow this. For example, in PHP you can read things like "if x===false" where the three equal signs mean "identical" (that is same value and same type). Just in case you ever wonder, there may be good reason to do so. ;-)Anonymousnoreply@blogger.com