LOL Booleans (21)

2 Name: #!/usr/bin/anonymous : 2008-03-27 15:11 ID:Heaven

Short answer is you shouldn't be adding booleans in the first place... but here's a summary of the behavior of various languages.

Languages in which true + true is true:

  • C: There's no boolean data type, but true is anything besides zero, and programs usually #define TRUE 1. Therefore TRUE + TRUE == 2, which is also nonzero -- and therefore also true. (but not necessarily TRUE)
  • C++: Mostly like C, but with an actual bool data type. Essentially it's just typedef enum {false, true} bool; which makes true 1 -- so again, true + true is 2.
  • Common Lisp: t + t returns t.
  • Python: True + True returns 2; Python handles anything non-empty and non-zero as True.
  • Javascript: true + true returns 2, which is a true value.
  • Perl: Like C, there's no real boolean data type. However, the canonical true value in Perl is 1, so true + true == true.
  • PHP: Again, true + true returns 2, which is also true.

Languages in which true + true raises an error

  • Ruby: true + true results in a NoMethodError. Additionally, booleans cannot be coerced into numbers (0 + true also throws an error)
  • Haskell: Same deal... you can't add to a boolean.
  • Lua: true + true results in the error "attempt to perform arithmetic on a boolean value".
  • Tcl: true and false are actually quite screwy, and personally I just use ints because it makes more sense to me, but I don't code in Tcl much anyway. However, [expr true + true] doesn't work, returning can't use non-numeric string as operand of "+".

Note that many languages in the latter category still interpret any non-zero integer value as true in an if statement, but if you're starting off with a boolean, you won't get to that point -- at least not without some amount of coercing.

So in summary, not one of the languages I have handy will evaluate TRUE + TRUE to FALSE, but several of them will result in an error of some kind. However it's still not generally a good idea to add booleans; after all, they're boolean, so you're better off using a proper boolean operator (e.g., i or j or equivalent).

This thread has been closed. You cannot post in this thread any longer.