[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
Don’t be mislead by that comment. It implies that a boolean variable takes up 1 bit instead of 32. But most probably it will take 8 bits. You’re still “wasting” 7 bits instead of 31.
Good point. Yeah, my “probably” is doing a lot of heavy-lifting there. In reality we don’t really know the length of a bool nor an int type in C. Likely a bool is 1 Byte and an int is 4 Bytes. But that depends on the architecture and compiler. The bool it guaranteed to hold 0 and 1, so it must be at least 1 bit. But with how addressing works, it ends up being 8 bits (1 Byte) anyway. If we want to be more efficient than that, I believe we have to code something with bit fields. It’s a bit out of scope for a beginner, unless you do microcontroller stuff.