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 complete beginner and I have no real reason why I would or would not want to deal with boolean variables, but I want to understand their raison d'être.

Edit: typo city

you are viewing a single comment's thread
view the rest of the comments
[–] 18 points 8 months ago* (last edited 8 months ago) (12 children)

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. (Edit: Though your bool will most likely take 8 bit anyways due to other things.) 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 always equal True. Or you do weird things to handle values other than 0 and 1 in the operations. All of that can be avoided and the code gets more readable with specific types.

There's nothing wrong with using ints, though. You just have to make sure the maths stays consistent.

  • source
  • hideshow 12 child comments
  • [–] 8 points 8 months ago (2 children)

    First, if you do it with an int, you’re probably using up 32bits per value.

    One project I worked with stored boolean values as bits in an 8-bit int, and then used binary math to read and write individual bits from that int, with each bit representing a distinct and independent boolean variable.

    Really weird, complicated, and sounds kind of dumb ... but it worked, and it was extremely memory-efficient.

  • source
  • parent
  • hideshow 2 child comments
  • load more comments (1 reply)
  • load more comments (10 replies)