In the C programming language, int values double up as boolean values.
I've been told this is bad.
But why is it bad?
At first, I thought of course it's bad, but couldn't think of any examples
illustrating why it's bad.
Could you help me find some examples?
As far type systems in general are concerned.
float can both get implicitly converted to
int in C'
Tried in python with static type checking (mypy). That too has no complaints to make:
def incr(num: int) -> int: return num + True incr(2) # 3
The simple answer is: the more relaxed a type system is, the less the type checker can check for errors at compile time.
A few examples:
if(a=b) is legal C code, but probably not what you want - most compilers warn about this, though. When an
if would only take booleans, the example would not be legal C code and one would not need funny extra warnings. Actually C and C++ compilers are these days full of "are you sure this is what you want" warnings one would not need if the type system would be reasonable.
if(a&b) is legal C code - and sometimes even what you want (say check
a&1 to see if a is odd) - but it might also be a typo which could have bad effects if one does not know that 0 and 1 are used for false and true in
But bool vs int is not what makes the difference between a weak and a strong type system. I wrote C++ for many years and when I switched to OCaml I thought "How could I waste years and years writing C++ code?". C++ does have separate bool and int types and even things like templates, but this makes its type system in no way even close to OCaml or Haskell. The OCaml debugger is so terse because one hardly ever needs it - quite to the contrary of C++. If OCaml code type checks, it usually does what you want.
bool is a subclass of
int, that's why your example typechecks.
I don't know if "bad" is the appropriate word here. int should not be bool because, well, int is different from bool! That bool is usually implemented as an integer should be thought of an implementation detail.
bool is the type with two values, and a type system should just treat it as that. By making a bool an int at the type system level, you're leaking implementation details into a higher level of abstraction, which is generally not desired.
Last updated: Nov 29 2023 at 19:01 UTC