[Beginner, C] If we can represent true/false with 1/0, why do we need the stdbool library and boolean variables?

https://programming.dev/post/47210489

[Beginner, C] If we can represent true/false with 1/0, why do we need the stdbool library and boolean variables? - programming.dev

I saw one example int x = 10; int y = 5; bool isGreater = x > y; printf("%d", isGreater); But I could write this int x = 10; int y = 5; printf("%d", x > y); I am a compete beginner and I have no real reason why I would or would not want to deal boolean variables, but I want to understand their raison d’être.

I think there are several reasons. First, if you do it with an int, you’re probably using up 32bits per value. You’d need 1 but waste the other 31, they needlessly take up storage. And then sometimes it’s nice to be expressive. So no one needs to remember if 1 is True or 0, or if True is greater than False, whether 2 or -1 map to True or False. And you end up in situations where either 2 equals 1, or True isn’t equal True. Or you do weird things with Undefined. All of that can be avoided and the code gets more readable with specific types.
Very nice point about the memory/storage usage! Also, I didn’t realize one can “map” other values as true/false than 1/0. But then again, I know very little at this moment. XD
Sure. As far as I remember in C, 0 is False. Every other number is True, you can use 1 or 42, doesn’t matter, they’re all “true”.
Except that a lot of the cstdlib functions return an int, where 0 == success, and negative numbers are falsy.

The way I make sense of it, is we sometimes return failure (i.e. from main). So 0 is no failure (aka success) and we can use the same thinking. The correct, expressive way to write it is probably use “EXIT_SUCCESS” and skip the ones and zeros. Pretty sure this comes from Unix. And with a lot of the other functions in cstdlib it’s the same way as using integers as booleans. For example a “malloc()” will either return your memory or a null pointer and the 0 is the special failure case.

But IMO the programming language shows its age and the context it was used in. More modern programming language design tends to be more strict with the types. Differentiate between interfacing with Unix stuff and other kinds of values. And we got more powerful concepts to deal with errors.

Malloc return 0 is a failure, but open return 0 is success. It’s just inconsistent, and it’s definitely an age and context thing.

Rust’s Result api are a pretty great solution. Not sure what other options are out there though.