Why use Bool in C if i could just use int?
Posted by Exotic-Ad9019@reddit | learnprogramming | View on Reddit | 68 comments
Why would i have to use the Bool type and have to add the header file of it if i could just make a const int = 1 which is restricted to only being 1 which would mean that it can and is only true . Just was wondering since i am new to C coding
InternetSandman@reddit
A few weeks ago at work I found an absolute gem in our codebase:
typedef int BOOLI desparately want to show whoever wrote that code all of the replies here and ask them what drugs they were on when they wrote that.
marrsd@reddit
For the top-voted reason, but it's helpful to know that C originally didn't have a boolean type, and did what you already suggested. True and False are still technically the equivalent of
!0and0.There are still functions in C that return values such as
NULLand-1for errors, or not-found conditions.sessamekesh@reddit
"Get the code to work" is a pretty low bar in most software development, and all the computer cares about. You can use an int just fine, and at some level that's what's always happening under the hood.
A lot of programming is more about making the code clear so that humans can understand it. "Bool" communicates "either/or" to a human much better than "int".
esaith@reddit
Yup. Because 0 is false and 1 is true for some folks. Some day, someone will state 1 is true and 2 is false. Then you'll have someone go, ok, well, -1 will be unset/null/undefined for variables that have been declared but yet initialized to a real value.
IAmADev_NoReallyIAm@reddit
More accurately 0 is False, True is (generally) defined as Not False... whether that is 1 or -1 or 2 or 100 ... is... varies... some languages have it as -1, others at 1. Some use a truthy value. That's why you can get away with boolean expressions that evaluate down to a non-zero value like if a * b then ... where a = 1 and b = 7 ... evaluate to true.
Demiu@reddit
But you see, 0 is false as in "no error", and everything else is true as in "yes error"
Except, when it's not
esaith@reddit
"The except when it's not" is when you laugh out loud while debugging and wonder how you got here.
Requirements change little by little that you're left with a mess
syklemil@reddit
Yeah, part of the issue is that in a boolean situation you need to be able to represent exactly two states, while an int lets you have billions of possible states, most of which are semantically identical and therefore superfluous … until you have to debug something that should be 1 but is actually -315 or 48371 or whatever.
(Though with C's weak typing you might be stuck with that anyway.)
Rhemsuda@reddit
Because an integer has potentially billions of possible variants and a Boolean has 2.
Start thinking of programs in terms of cardinalities of sets and you will save yourself a lot of head scratching. 2 possible variants is better than billions. Always use as few variants as possible if you can.
Otherwise, you’ve answered your own question. You CAN use an int, it’s just bad practice
Outside_Complaint755@reddit
Same reason we don't typically use
uint_8instead ofchar. By using the bool type you are making it explicitly clear that the variable (or parameter being passed to a function) is a True/False flag.Silly_Guidance_8871@reddit
Yeah, it's never a good idea to confuse representational equivalence with semantic equivalence.
HalfRiceNCracker@reddit
Well put
panda-goddess@reddit
well, my C teacher loves using 1 and 0 as flags instead of booleans, so I guess go for it
but I just despair, it really is bad for legibility
Maggie7_Him@reddit
Using bool makes your code way more readable and self-documenting. When someone sees a bool variable, they instantly know it's true/false. With int, they have to guess if 0 means false or if you're using other values. Plus, bool is the standard since C99—helps catch bugs at compile time. Welcome to C!
Maggie7_Him@reddit
Using bool makes your intent crystal clear — when a variable can only be true or false, bool communicates that immediately. With int, readers have to guess what your 0s and 1s mean. Since C99, stdbool.h gives you proper bool, true, and false keywords. It also helps static analyzers and IDEs catch type mistakes. A small habit that pays off in larger codebases!
ExitPsychological192@reddit
Using bool from stdbool.h instead of int is about communicating intent clearly. When you declare a variable as bool, you signal to every future reader that this holds a true or false state, not an arbitrary number. Some static analysis tools can also catch mistakes with _Bool that they cannot with plain ints. There is a subtle semantic difference: assigning any nonzero value to _Bool gives you 1, so the type enforces proper boolean semantics. Think of it like using size_t for sizes rather than plain int. Both compile, but the right type expresses intent and makes code easier to reason about.
_TheNoobPolice_@reddit
You don’t need to, in fact it’s idiomatic C in kernel land to use ints where stdbool.h isn’t a thing. Using the BOOL and BOOLEAN typedefs in WDK are really just ints and char respectively and using them interchangeably is a common cause of bugs.
explicit17@reddit
Why write words at all when we can write ones and zeros
throwawayacc201711@reddit
That’s it! Time to write assembly only
FloydATC@reddit
Ooh look at mr fancy pants here! Machine code suddenly not good enough for you huh? /j
WowAbstractAlgebra@reddit
Mr Fancy Pants making fun of someone when they deem binary too "low level" for them.
desrtfx@reddit
No, Machine Code in Binary via Switches it is.
Yet, https://imgs.xkcd.com/comics/real_programmers.png
XilamBalam@reddit
Why say lot words when few do trick?
probability_of_meme@reddit
When me president, they c++
PM_ME_UR__RECIPES@reddit
It's for legibility. Code doesn't just have to work, it has to be understood and maintained by yourself and other future developers. If you type something as a bool, then it's more clear how that variable is meant to be used, and people are less likely to do stupid things with it like adding and subtracting, or doing bitwise operations
HappyFruitTree@reddit
To make purpose more clear and you don't need to worry about other values than 1 or 0.
dariusbiggs@reddit
using correct static typing makes both the intent clear and the readability and maintainability of the code.
ironnewa99@reddit
I mean I’ve used uint_8 for booleans before but it was under a global #define BOOL uint_8
It was also for a driver on a chip so it’s a bit different.
Learning how to program is part syntax and all but a lot of it is how to solve a problem and how to convey your solution
Majestic_Rhubarb_@reddit
False is zero, not false is true … true is not 1 … but 1 is true.
That’s why we use std::bool, not Bool, BOOL or bool
nicodeemus7@reddit
Because someone will inevitably enter "2"
Wulf2k@reddit
For the same reason that you don't define it as a string containing the text "Yo, this is absolutely true."
Because it's inefficient and slightly weird.
You can fit 32 bools in the space of an int.
Difficult-Mango312@reddit
4 bools in the space of an int.
You could bit flip and use an int to get 32 “bools”.
Wulf2k@reddit
Yes, 32 bits gives you 32 bools.
Lots of games still use bitfields for consecutive bools.
Difficult-Mango312@reddit
Not actual bool types though, just a bit you use like a bool.
Wulf2k@reddit
Compiler dependant.
Declaring 32 bools in a row has no real reason to not be compiled as a bitfield.
Difficult-Mango312@reddit
Compilers are not magic optimization machines. Do you have a reference to a compiler that will take 32 Bool objects and compile it to a bitfield behind the scenes?
Wulf2k@reddit
struct Flags { bool isActive : 1; bool isVisible : 1; bool isValid : 1; };
I suppose not, but that'd do it, and those are perfectly valid bools
CarnivorousGoose@reddit
There is definitely a reason why a compiler wouldn’t do that, given that it behaves quite differently. For example, when working with pointers to those booleans, which wouldn’t be possible if stored as individual bits.
blablahblah@reddit
Theoretically yes, but in practice, memory can only be addressed by the byte so you can't have variables smaller than 1 byte. Unless you're using bit fields in a struct, but the whole struct still takes up a whole number of bytes.
Wulf2k@reddit
I still see bitfields used pretty regularly when modding games.
I assume the compiler automatically bitfields any consecutive bool declarations.
Icantbelieveitsbull@reddit
With most compilers books don't get squished down though, so they're often a whole byte, at which point using
(uint8_t >> N) && 1can be more efficientneuromancer-gpt@reddit
A bool is 1 byte, not one bit. But the essence of your answer is correct. Memory.
Sea-Attorney2788@reddit
it doesn't work as often...
OnYaBikeMike@reddit
It shows intent to somebody reading the code.
speedyrev@reddit
Communication that this will be true or false and nothing else.
ExtraTNT@reddit
Types are the strongest form of documentation
High_Quality_Bean@reddit
Do it. Say fuck types, play with some bits directly, build a project, maintain it, see how it goes. Fuck around and find out.
Then try something super type heavy, java c#, rust, etc. Find out what types solve, what knew problems they introduce.
Tldr: the more you restrict a development environment the more "incorrect" behaviour you can eliminate (ideally without stopping correct behaviour), and the more you can cut down on spaghetti and enforce coherent structure. You'll likely find yourself doing illegal things to your bool by accident, the compiler not picking up on it, and weird bugs cropping up.
backfire10z@reddit
I write code for me to understand, not the computer. The computer is reading binary.
mlugo02@reddit
I essentially just use ints as booleans. I even just use 1 and 0 for true or false
Sad_School828@reddit
Quoting the ISO C standard:
`The header shall define the following macros:
bool Expands to _Bool.
true Expands to the integer constant 1.
false Expands to the integer constant 0.
__bool_true_false_are_defined Expands to the integer constant 1.
An application may undefine and then possibly redefine the macros bool, true, and false.`
So yeah, true is 1 and false is 0.
Pale_Height_1251@reddit
It shows intent.
dalekaup@reddit
Premeditated boolean
Thaerious@reddit
Most of the answers here are snarky. This is correct one.
autistic_bard444@reddit
You live in a time where no one cares about cpu and memory efficiency or even memory leaks. Back in the 90s, bytes counted, especially if they were getting lost
Technically a bool could use 1 byte instead of 2, but cpu arch does deal with single bytes well
In c a bool is 2 bytes. A short int registered as 0 or 1 is 4 bytes. This can scale differently in different compiler setups and languages.
In c++ inside of a struct, and I think a pointer, the compiler largen these for better handling. So the bool can go to 4+ bytes. The short int can balloon 8 to 12 or more.
C++ only requires stdbool include and operandi as a command
Technically in clang you can force it lower inside of a struct.
struct Flags { unsigned int foo : 1; };
I do not recall how this translates to obj-c or llvm and from gcc, as c++ can't natively use llvm
Clang is just a happier place over gcc though
Tl;dr. Memory efficiency used to be super crucial. Now no one cares
danzerpanzer@reddit
If you want to do something like that, I'd like to suggest that you use _Bool instead of int. _Bool can only hold 0 or 1. If you make your own Boolean type which is really an int, there's a risk that you could have two "true" variables assigned different int values and if you tested them for equality, they'd evaluate to being not equal even though they were both true.
The most recent C standard has a built in boolean type so you don't have to include a header file to get it, but I have no idea how much compiler support it has. In years past, there was a discrepancy between the language as officially defined and the language as actually implemented.
lukkasz323@reddit
You're adding unnecessary permissions to your code.
If there is a code that expects either if x == 1, or if x == 0, it might just pass silently when x is for example 2, or -4, which is terrible.
Such thing won't happen with a bool.
It's sometimes fine to use int for a set of bools (flags), when you're using the fact that an int has 32 bools in it, for each byte, so you can represent 32 true/false in it, not just 1.
EyesOfTheConcord@reddit
\if fieldIsPopulated === true\ at a glance is easier to understand compared to \if fieldIsPopulated === 1\
Difficult-Mango312@reddit
1 byte versus 4 bytes.
A bool simply tells you true/false, whereas an integer is a large range of values.
Including a header has no cost, except for during compilation which is negligible.
mjmvideos@reddit
You don’t have to at all. If you want to use 0 and not zero, go ahead- it’s the way it was done originally. But I’ll bet over time, you’ll come to appreciate the bool type and the clarity it provides.
tstanisl@reddit
To have
(bool)1 == (bool)2manchesterthedog@reddit
Why don’t you just use the value 1 or true if you’re trying to hardcore true? Is this for a while(true) type situation?
DonkeyTron42@reddit
In C you would traditionally use "for(;;)".
manchesterthedog@reddit
My bad, I was thinking c++
DonkeyTron42@reddit
Before C99, it was common place to just use ints as bools. C99 formally defined the bool type in stdbool.h and added some safety to provide compatibility with the C++ primitive bool type.
augustcero@reddit
human readability. especially when you're working with others on a project, that "quick" translation from 1 to true can pile up real fast as your project grows
Ratfus@reddit
Well, for starters, if you wanted a constant 1, you wouldn't use bool. Instead, you would use #define One 1. Consts (keyword const) aren't really constants in C and can be dangerous in arrays. Arr[const A=1] will make a variable length array for example, where Arr[1] will not.
In code, you would use bool to prevent items outside one/zero from being used. In assembly, variables don't exist, it's all just a data clusterfuck. Both strings and numbers go in registers, but this is dangerous. What if I accidentally pull a register with a character? It might print a number making the code look ok... but under the surface you've got strange shit going down.
DTux5249@reddit
For the same reason I don't create a Java class that can wipe my hard drive, and call it "Phil" in the program.
Using bool communicates how the data is meant to be used. And while there are some cases where batching booleans together as integers is useful, that isn't always the case.
MikeUsesNotion@reddit
Communicating semantics.