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
[–] 13 points 6 months ago* (1 child)

code is read more often that it is written. booleans are actually just integers under the hood but explicitly using booleans communicates your intent. you're saying to the next guy that "if this is something other than 1 or 0 something has gone wrong".

when it comes to C specifically, the bool type was a pretty late addition because as you say, an integer can do the job. but it's very good for organisation, and it also allows the compiler to make some assumptions about how the variable can be accessed. if you know something can only be in two states, you can shove a whole bunch of them into the same byte of memory.

  • source
  • hideshow 1 child comment