3 ms·
Having a distinct boolean type prevents this error (fortunately detectable with linters, so pay attention to your linter output): if(n = 5) { ... } When the
by Jtsummers 4y ago
Having a distinct boolean type prevents this error (fortunately detectable with linters, so pay attention to your linter output):
if(n = 5) { ... }
When the author probably meant:
if(n == 5) { ... }
In languages where the assignment statement can also be used in expressions (as it evaluates to the value being assigned) the above can create very subtle errors in a program. Having a distinct boolean means that the type system will reject that. Of course, it wouldn't reject this:
if(b = true) { ... }
But that's something you generally shouldn't write anyways (and, again, your linter will probably catch).
- eMSF 4y agoMany languages with distinct boolean types do not require that the condition expression in an if statement evaluates to that type, and hence do nothing to prevent that error.
- tialaramex 4y agoModern C actually has a boolean type, named _Bool (aliased bool if you ask for it explicitly) and yet sure enough despite this it figures '0', 100 and 0.1 are all truthy. Yes, what's critical here is that the only type that should be boolean true is the boolean value true, and your language is letting you down when it insists strings, or integers or some other type entirely should be "truthy" because it was easier than writing what you meant - soon or later this type laziness will bite you. I think this is more obvious in languages with pattern matching where the boolean if condition is just the world's least interesting pattern match, clearly (69, "Nice", true) doesn't match (true, true, true) as a pattern and is instead a type error.
- adrian_b 4y agoThe possibility of writing by mistake an assignment in a condition test is something strictly specific to C and derived languages and this is without doubt one of the greatest errors in the design of C. In any language that keeps the Algol notation, i.e. where "=" is a relational operator and ":=" is assignment, this kind of mistake is extremely difficult to make and easy to notice when it happens nonetheless. So the fact that a programming language can have a bad notation for equality that leads to mistakes cannot be used to justify unnecessary complications in different kinds of Boolean expressions.