Stream: Miscellaneous

Topic: Why int instead of bool bad?


view this post on Zulip Julin S (Nov 10 2022 at 04:59):

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?

view this post on Zulip Julin S (Nov 10 2022 at 05:00):

As far type systems in general are concerned.

view this post on Zulip Julin S (Nov 10 2022 at 05:04):

Likewise char and float can both get implicitly converted to int in C'

view this post on Zulip Julin S (Nov 10 2022 at 05:42):

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

view this post on Zulip Michael Soegtrop (Nov 10 2022 at 08:15):

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:

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.

view this post on Zulip Li-yao (Nov 10 2022 at 08:16):

In python, bool is a subclass of int, that's why your example typechecks.

view this post on Zulip Xuanrui Qi (Nov 18 2022 at 15:56):

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.

view this post on Zulip Xuanrui Qi (Nov 18 2022 at 15:58):

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: Apr 20 2024 at 08:02 UTC