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

  • calcopiritus@lemmy.world
    link
    fedilink
    arrow-up
    3
    ·
    14 hours ago

    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.

    • hendrik@palaver.p3x.de
      link
      fedilink
      English
      arrow-up
      1
      ·
      edit-2
      12 hours ago

      Good point. Yeah, my “probably” is doing a lot of heavy-lifting there. Thx, I’ve added a short sentence.) 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 they do microcontroller stuff.