+ 2
Why use bool(ean) in C++ ?
If something like bool passed = false; essentially returns a 0, why not just use: int passed = 0; Memory? So that variable cannot be altered? What is the main use of bool?
7 Answers
+ 8
Having a strong definition will help to understand what this code is supposed to do.
If you declared a passed variable as a bool, I can tell instantly that there is only two state for it.
If it's an integer, I might ask myself "why could it be more than 1?"
Strong typing definition also helps you and your colleague to avoid making mistakes on larger projects.
It's also useful for understanding the logic of your code!
fun fact: a bool takes as much space in memory than an integer.
I hope this helps :)
+ 7
Apollo-Roboto afaik C++ standards never mentioned about how much memory does any data type ( apart from char ) should take, so it should totally be up to your implementation to use as much bytes as they need to implement the data type properly.
https://code.sololearn.com/cqHI7JfV995i/?ref=app
+ 6
It is indeed mostly the same size as that of char which is by standards defined to be the smallest addressable value in the language, you can't have a data type smaller than that ( though there exist some exceptions but there is practically no use case of such data type in modern systems and is only used in very special cases )
+ 4
If i got your question correctly ,
You can use std::boolalpha for that if you want to get result as true / false rather than 1 or 0
https://code.sololearn.com/cX0QVMNyA3FA/?ref=app
+ 3
First of all, using right type for a variable will help you and everyone else to quickly understand what type of "work" that variable is used for.
So if you use Boolean instead of Integer you don't have to look deep into your code to understand that this variable is used to check if something is true/false.
Secondly, the size of Boolean is smaller than that of Integer. You can run this code to check it out: https://code.sololearn.com/cZc7zvjAaL4n/?ref=app
+ 1
oops, you are right I had to look it up myself. I forgot int is 4 bytes, but it does seems to be the same size as a char
+ 1
Prashanth Kumar
I am very new to programming, only a few weeks. In the introductory lessons they tell what bool does but do not really explain why it would be used as opposed to just using an int variable of 1 or zero. But hopefully I'll understand in time, some of the answers here have helped explain.