In real-life, it’s common to ask or be asked questions that can be answered with “yes” or “no”. “Is an apple a fruit?” Yes. “Do you like asparagus?” No.
Now consider a similar statement that can be answered with a “true” or “false”: “Apples are a fruit”. It’s clearly true. Or how about, “I like asparagus”. Absolutely false (yuck!).
These kinds of sentences that have only two possible outcomes: yes/true, or no/false are so common, that many programming languages include a special type for dealing with them. That type is called a Boolean type (note: Boolean is properly capitalized in the English language because it’s named after its inventor, George Boole).
Boolean variables
Boolean variables are variables that can have only two possible values: true, and false.
To declare a Boolean variable, we use the keyword bool.
1 |
bool b; |
To initialize or assign a true or false value to a Boolean variable, we use the keywords true and false.
1 2 3 4 |
bool b1 { true }; bool b2 { false }; b1 = false; bool b3 {}; // default initialize to false |
Just as the unary minus operator (-) can be used to make an integer negative, the logical NOT operator (!) can be used to flip a Boolean value from true to false, or false to true:
1 2 |
bool b1 { !true }; // b1 will be initialized with the value false bool b2 { !false }; // b2 will be initialized with the value true |
Boolean values are not actually stored in Boolean variables as the words “true” or “false”. Instead, they are stored as integers: true becomes the integer 1, and false becomes the integer 0. Similarly, when Boolean values are evaluated, they don’t actually evaluate to “true” or “false”. They evaluate to the integers 0 (false) or 1 (true). Because Booleans actually store integers, they are considered an integral type.
Printing Boolean variables
When we print Boolean values with std::cout, std::cout prints 0 for false, and 1 for true:
1 2 3 4 5 6 7 8 9 10 11 12 |
#include <iostream> int main() { std::cout << true << '\n'; // true evaluates to 1 std::cout << !true << '\n'; // !true evaluates to 0 bool b{false}; std::cout << b << '\n'; // b is false, which evaluates to 0 std::cout << !b << '\n'; // !b is true, which evaluates to 1 return 0; } |
Outputs:
1 0 0 1
If you want std::cout to print “true” or “false” instead of 0 or 1, you can use std::boolalpha. Here’s an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#include <iostream> int main() { std::cout << true << '\n'; std::cout << false << '\n'; std::cout << std::boolalpha; // print bools as true or false std::cout << true << '\n'; std::cout << false << '\n'; return 0; } |
This prints:
1 0 true false
You can use std::noboolalpha to turn it back off.
Integer to Boolean conversion
You can’t initialize a Boolean with an integer using uniform initialization:
1 2 3 4 5 6 7 8 9 |
#include <iostream> int main() { bool b{ 4 }; // error: narrowing conversions disallowed std::cout << b; return 0; } |
(note: some versions of g++ don’t enforce this properly)
However, in any context where an integer can be converted to a Boolean , the integer 0 is converted to false, and any other integer is converted to true.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#include <iostream> int main() { std::cout << std::boolalpha; // print bools as true or false bool b1 = 4 ; // copy initialization allows implicit conversion from int to bool std::cout << b1 << '\n'; bool b2 = 0 ; // copy initialization allows implicit conversion from int to bool std::cout << b2 << '\n'; return 0; } |
This prints:
true false
Inputting Boolean values
Inputting Boolean values using std::cin sometimes trips new programmers up.
Consider the following program:
1 2 3 4 5 6 7 8 9 10 11 |
#include <iostream> int main() { bool b{}; // default initialize to false std::cout << "Enter a boolean value: "; std::cin >> b; std::cout << "You entered: " << b << '\n'; return 0; } |
Enter a Boolean value: true You entered: 0
Wait, what?
It turns out that std::cin only accepts two inputs for Boolean variables: 0 and 1 (not true or false). Any other inputs will cause std::cin to silently fail. In this case, because we entered true, std::cin silently failed. In C++11 or newer, a failed input will also zero-out the variable, so b also gets assigned value 0. Consequently, when std::cout prints a value for b, it prints 0.
Boolean return values
Boolean values are often used as the return values for functions that check whether something is true or not. Such functions are typically named starting with the word is (e.g. isEqual) or has (e.g. hasCommonDivisor).
Consider the following example, which is quite similar to the above:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
#include <iostream> // returns true if x and y are equal, false otherwise bool isEqual(int x, int y) { return (x == y); // operator== returns true if x equals y, and false otherwise } int main() { std::cout << "Enter an integer: "; int x{}; std::cin >> x; std::cout << "Enter another integer: "; int y{}; std::cin >> y; std::cout << std::boolalpha; // print bools as true or false std::cout << x << " and " << y << " are equal? "; std::cout << isEqual(x, y); // will return true or false return 0; } |
Here’s output from two runs of this program:
Enter an integer: 5 Enter another integer: 5 5 and 5 are equal? true
Enter an integer: 6 Enter another integer: 4 6 and 4 are equal? false
How does this work? First we read in integer values for x and y. Next, the expression “isEqual(x, y)” is evaluated. In the first run, this results in a function call to isEqual(5, 5). Inside that function, 5 == 5 is evaluated, producing the value true. The value true is returned back to the caller to be printed by std::cout. In the second run, the call to isEqual(6, 4) returns the value false.
Boolean values take a little bit of getting used to, but once you get your mind wrapped around them, they’re quite refreshing in their simplicity! Boolean values are also a huge part of the language -- you’ll end up using them more than all the other fundamental types put together!
We’ll continue our exploration of Boolean values in the next lesson.
![]() |
![]() |
![]() |
So I'm superbly confused, I notice in the answer to the question he initializes a statement of:
Why is this necessary? When I write the code as follows it executes correctly, despite not having that statement included... I'm just confused as to any pros/cons with including or not including that statement. This is my code that ran properly:
Using the prime variable isn't necessary. It was a stylistic choice that I employed to try and make each statement a bit simpler to understand.
If I were writing this code for myself, I would have written it as you did -- without the intermediary variable.
Hi Alex
I don't think this quiz is fair
because you have not taught us yet about multiple "if's"
Why would you assume that you can only use one if statement per program or function?
A function is just a sequence of statements -- those statements can be if statements, or any other kinds of statements.
Hi :)!
What does ''trip up'' means? Is it to scare?
Why don't you use endl in those?
Hi R310!
> What does ''trip up'' means?
Where are you reading that?
> Why don't you use endl in those?
@std::cin::operator>> waits for the user to press enter. When the user presses enter, a line feed is inserted into the console already. Outputting a line break would result in an empty line.
I get it.
In the article you wrote that it trip up new programmers!
"trip up" means to "cause someone to get stuck or make a mistake"
Oh sorry I saw this one after...
hi, is this solution valid?
Hi Jörg!
No it's not. The , operator is not an "or". Use ||.
Okay, thank you
Hello !
“Consequently, when we print boolean values with std::cout, std::cout prints 0 for false, and 1 for true:”
In the program that you wrote below the above statement I noticed that you did not initialize any variables with the data type “bool”. Then how does std::cout know that it has to print 1 when in the cout statement we only wrote true ? Is it possible that if we wrote std::cout <<“true”<< instead of just std::cout <<true<<, std::cout would print true and not 1?
Hi Aditi!
When you write
The "true" is treated as a string and it will be printed as such.
When you write
The "true" is a bool, @std::cout will print a bool and @std::cout does so by printing the numeric value (0 or 1).
As mentioned in the lesson, you can also use @std::boolalpha to print bools as "false" and "true".
Right ! I get it now . Thank you !
Something interesting I've noted... Looks like I don't get garbage back when I enter a non-boolean value as input. Using the latest (as at posting) version of MingW/g++.
It appears to be converting the input string into a number first, then doing the (zero-or-empty == false) thing. I'm somewhat experienced with PHP, and know that it is implemented in C/C++, so given the way that PHP casts strings into numbers, and non-booleans into booleans, these results are actually unsurprising to me...
Input == Output
------------------
0 == 0
1 == 1
2 == 1
a == 0
-5 == 1
+8 == 1
45674513 == 1
asdfasdl == 0
456asdf == 1
asdf456 == 0
Un-related, looks like the edit box on this site has a bug - it ignore the [code] tags, breaking the code formatting.
Hi Kage-Yami!
In order to figure out what's actually happening and what's supposed to happen one would have to dig through the standard and implementations, I don't feel like doing that now.
A bool is an integral type, so number extractions into a bool works, but they leave the input stream in a failed state (You can check it with @std::cin.fail()).
Code tags display only after refreshing the site if they were added in an edit.
Interesting... thanks for the tip!
Here is how I solved the quiz. Any suggestions?
Hi Jhayar!
Looks similar to others solutions.
It is good to have it here, some people can find it interesting.
@nascardriver this time I did initialize all of them :), have a good day!
As you know, boolean expressions are expressions
You are checking if
will be true. If it is true you are returning false, why not try something like this
That way if it is prime, it will be true. Then you can do this
to invert. Or if you like compact code.
Then also, you must remember that
, so
id the same as
becomes
which can become
means "if x divided by i returns 0 it's not prime/is false"
This makes the code much more concise. And remember that comments at the code level should explain why, so a comment like "If it's modulus is 0 it's not prime" makes the intent of the code clear.
I though it be fun to make it check for any user inputed integer to see if it's a prime.
It uses some not yet explained things like a for loop and and modulo but should make enough sense.
So here is my aproach to the assignment (from my testing it works). and hope it is use to someone who is trying something similar :D
also was a fun little program to write.
Hi Levi!
Some suggestions:
Thanks man These are some sweet surgestions. it makes sense to only count to the square root as that is the largest division possible.
also cleaning up some of the code was nice shows me how to make my code nicer in the future.
A small adjustement over nascardrivers's code
I removed his comments to emphasize mine
After compilation it's the same. I prefer the first variant, because it's easier to understand what the condition is.
@alex, @nascardriver, I wrote below mentioned program to tell if a number is prime or not and we can check any number lesser than max size of int.
I understand that Nascardriver might not have used structs/recursion/function in your program because these concepts are not introduced yet. But I thought that my code should have been faster to detect large prime numbers, instead, @nascardriver's program is way faster than mine. I do not quite understand why.
Reason I think my code should have been faster for large prime number:
I divide the large prime number by 2,3,5,7 and so on and calculate the largest prime number which could divide the number user has input to be 1/2, 1/3, 1/5, 1/7 and so on. Thereby reducing the amount of checks that I do.
Whereas Nascardriver is checking till number_to_be_checked/2, which can be a lot of numbers when the number_to_be_checked is large.
So my question is, I do not understand why Nascardriver's code takes less amount of time than mine, is it because I'm using many variables and function calls?
my code:
Hi Shri!
The biggest slow-downs in your code are recursion and dynamic lists. Both can be terribly slow. If you're using dynamic lists, you should reserve enough space beforehand so the underlying array doesn't have to be resized.
Hey Nascardriver,
Thanks for the reply! Thanks for clarifying that recursion and dynamic lists require lot of time.
1 point I wanted to clarify with you is regarding your comment:
If you're using dynamic lists, you should reserve enough space beforehand so the underlying array doesn't have to be resized.
From a bit of googling around I found that std::list (which I have used) provides us with doubly linked list. I have not studied Data structures yet, but from what little understanding I have, I think doubly linked lists do not require reserving memory beforehand unlike say dynamic array.
So by this comment of yours:
If you're using dynamic lists, you should reserve enough space beforehand so the underlying array doesn't have to be resized.
Which array are you referring to that I have used in my code?
> I found that std::list (which I have used) provides us with doubly linked list
I didn't know that. In that case there's no need to reserve memory beforehand. Still, a doubly linked list needs to store the value and two pointers for each element, meaning that 20 bytes (assuming 64 bit) have to be allocated for every prime number found. Overall your logic seems to be overly complex for the task you're trying to achieve.
I wouldn't have
I would rather have a variable and set that to false, and the break out the loop. That way we have a single exit point, which makes debugging much easier. If there were multiple instances where false could be returned, then this can be confusing as to what return statement was executed.
Here is mine:
Hi, i know we not covered the for loops but i want to know if my code it's ok, thank you.
You are doing a great job!!
Hi Stefan!
From lesson 2.1: "If you’re using a C++11 compatible compiler, favor uniform initialization".
Your loop only needs to run up to sqrt(x).
@static_cast<int> converts the given value to an int. I do this, because @std::sqrt returns a double.
You need to include <cmath> to use @std::sqrt.
References
* Lesson 2.1 - Fundamental variable definition, initialization, and assignment
* Lesson 4.4a - Explicit type conversion (casting)
* @std::sqrt http://www.cplusplus.com/reference/cmath/sqrt/
Thank you very much for your answer!
Do you teach System() commands in this tutorial??
Hi Max!
You can check out the @std::system documentation here http://en.cppreference.com/w/cpp/utility/program/system .
Other than that there's not much to talk about, because all it does is forward a command to the OS which has nothing to do with C++.
Thanks
I just spent the past hour ringing my brain for an answer to this quiz on this section. I built so many solutions and none of them would function properly.
It was only when I finally gave up and clicked to see the answer that I realized you left a hint after the question...
So TIL how that you can add multipart if statements to a bool function and that you should always read the entire quiz before answering the first question.
Thank you, Alex.
Why you use return false in bool isPrime function?
Hi Samira!
@isPrime has to return a value. If @x isn't 2, 3, 5 or 7 @isPrime won't return true and it does not return anything automatically.
Oh, I see! Thank you nascardriver. But can I use else statement instead of return? which one is the best practice? return or else statement?
If you used else you'd still have to return. No matter what happens in a non-void function, you have to return (You'll learn about exceptions in the future).
Hi! I've been learning C++ here the last 2 days and i think i'm really making good progress thanks to you.
I wanted to share the code i did for the exercise if you could tell me if that's a good thing for a first time.
Hi Bennhyon!
@sayIfPrime looks good, I made some changes to your @main function:
I think you should put the "you silly" comment right after they enter a number, and make them fix it.
If you want to know how to do loops in code, you can look for "while loops c++" on google, or directly on this site. http://www.learncpp.com/cpp-tutorial/55-while-statements/
Thanks. I'm actually going through the whole tutorial on this page right now and just haven't gotten to loops yet, but I'll get there.
Hi Alex,
What do you think of this solution?
bool isPrime(int x)
{
return (x == 2 || x== 3 || x== 5 || x== 7);
}
int main()
{
int x;
std::cout << "Enter a single digit integer: ";
std::cin >> x;
if (isPrime(x))
std::cout << x << " is a PRIME number!";
else
std::cout << x << " is NOT a prime number!";
return 0;
}
I always forget that you can assign a function to a variable, so the only way I found out to do the exercice was this one^.
Is that okay?
This code looks great. I didn't use logical OR in my solution because it's not covered until next chapter.
Thanks for the fast reply, Alex!
Great tutorials, by the way. The best for c++ since it explains everything well and gives so many exercices (which many tutorials don't offer). These exercices are a freaking crucial point in learning this seemingly hard programming language. :D
Hi me again,
I don't really know where to ask this so...
I want to be able to make my function return a text and I don't know how.
Hi Gabe!
I'll have to use content from future lessons for this since it hasn't been covered yet.
Option 1:
Option 2:
Or don't return a string at all
General issues with your code
Hello, I'm back
I took a break from this because it was frustrating. I realized I could make my life easier and have qOne() return a boolean and have that boolean decided what main would output. But I can't seem to make qOne run then call the return value to use in main.
Is this what you're looking for?
References:
Lesson 1.4 A first look at functions and return values (Section "Reusing functions")
Thanks!
Hi,
My code looks some what different to the solution. Running from a previous lesson, I thought that it was bad practice to have anything within the main function, other than calls to other functions? I thought that it should be seperated. Here is my code:
what would be the best practice / what would be expected if you was a software engineer?
Cheers,
G
There's little point in having a main do nothing but call a single other function. In that case, you might as well put the logic in main.
Most often in production code I've seen, main looks something like this:
But since our programs don't tend to have initialization and cleanup needed, our main() can just be the contents of doWhatever().
Hi Alex,
why do I have to return false at the end of the function?
Hi Ali!
I assume you're talking about @isPrime.
@isPrime has been declared to return a bool
No matter what happens inside the function, it has to return a bool in every case (except when an exception is thrown)!
If we were to remove the "return false;" and none of the numbers were matched @isPrime would not have a return value, this in turn would cause undefined behavior which, in the best case, causes a crash. Worst case, it works fine for you but crashes on other machines and you'll have a hard time figuring out why it's working for you but not for others.
And why do I have to return true in every other case?
Because @isPrime is supposed to tell you if @x is a prime number.
Returning true means that @x is a prime, returning false means @x is not a prime.
Oh now I get it thank you :)
Hi siriusbuisness!
Your compiler will generate the same output for both variants so there's no difference.
However, when using an intermediary value you can view the variable in a debugger which is not as easy when using the return value of isPrime directly.
Hi Alex (and others)
In my solution for this chapter’s quiz I used
whereas you used an intermediary value
Is the intermediary value better convention for if statements?
Thank you for your time and the tutorials.
Please edit your posts instead of re-posting them, the reply to your question is above.
Thanks for your swift answer. I tried editing but for some reason the code wouldn't format properly afterwards so I re-posted.
No, in most cases I'd write it as you did (unless I needed to save the result of the isPrime() call for later).
I used an intermediary bool here just because it's a bit easier for learners to understand.
Here's how I did it.
What's the different between adding curly braces and no curly braces around the statement after if?
Hi Karston!
The curly braces are required if you want to execute multiple lines:
Output:
cats
Output:
like
cats
Please use curly braces for readability and extensibility.
To your code:
Your isPrime function doesn't work
(x / x == 1) Is true for any number, doesn't have an effect.
(x / 1 == x) Is true for any number, doesn't have an effect.
(x / 2 == 1) Is equivalent to ((x == 2) || (x == 3)) // 3, because (3 / 2) == 1. An int cannot hold 1.5 so it's floored to 1.
Your program doesn't accept 5 or 7 as prime numbers, have another try.
Initialize your variables.
Hello,
Thank you for your correction, fixed!
If that condition"if" has only one statement, then there is no need of using braces there..
But let's assume that u have more than a single statement, if you want them to execute only if the condition is satisfied, then u should go for curly braces..
For a single statement it is not mandatory to keep braces
Hey Alex!
So I've tried to make a program that checks if a number is a prime.
The problem seems to be that in checkPrime() it ignores the for loop that I've made, which results in wholeDivisions always being equal to 0.. What am I doing wrong?
Hey Alex!
I managed to fix it myself :D
My mistakes were:
1. In my for loop I wrote:
but it should be:
2. I started
at 0, which resulted in dividing by zero.
3. And I don't quite get this one: I made 'input' and 'i' integers which for some reason made my program treat division1 like and integer (5/2 = 2, for example). I fixed that by making 'input' and 'i' floats. But could you explain why it was treating division1 like an integer?
So yea now it works :)
Hi Riux!
When you divide an int by and int the result will be an int. As you figured, this can be fixed changed by having the dividend or divisor being a float.
I don't know how the result type is determined so I wrote a test program.
This produces the output
It appears the result will be of the type of the dividend or divisor with the highest precision. (int < float < double)
PS: Please edit your posts instead of deleting and re-writing them.
Thanks nascardriver :D!
So if the result will be of the type of the dividend/ divisor with the highest precision, then that means that I could only change 'i' into a float and leave 'input' as an integer and the result would still be a float right?
And I'm curious does deleting and rewriting your comments cause problems? I mean I will obviously stop deleting them now but I'd just like to know.
Correct, but don't loop floating point numbers unless you have a good reason to do so. Instead, cast one of the variables to a float while doing the calculation:
You'll learn about casting in lesson 4.4a, if you think this is overkill for now you can keep doing it with floating point numbers in your loop but you shouldn't get used to it.
Here's the comment problem:
- You post
- UserX presses reply and starts writing their comment
- You delete and repost
- The comment entered UserX cannot be added as a reply, because the original post doesn't exist. The reply will be published as a regular comment and you won't receive a notification.
Great thanks a lot!
I think I'll keep my method for now.. maybe I'll change it after 4.4a.
And thanks for explaining the comment problem :)
> I don’t know how the result type is determined so I wrote a test program.
I cover this in lesson 4.4 under the subsection, "Evaluating arithmetic expressions".
You're basically correct, but the list in that lesson is a little more comprehensive.
Dear Alex,
thank you very much for your helpful tutorial.
I’ve got a question about the following little program:
When I enter 1 it says "The input is true.", and when I enter 0 it says "The input is false.", as expected. What I wonder about is that the program takes every number, even negative numbers and fractions as true, except those that begin with 0. And every letter is considered false. I thought that if I don’t enter 0 or 1, "input" would be any random number because it wasn’t initialized. But why is then every letter false and every number true except 0?
In C++, bool is an integral type, meaning your input is treated as an integer. That means integer 0 is treated as false, and other integers (including negative ones) are treated as true.
Letters are invalid inputs in this context, and cause no input to be assigned to your variable. Thus, input remains uninitialized. This will cause undefined behavior when you use it later (to compare against false or true).
Teacher,
Thanks for your excellent work with this great site.
What do you think about this answer to your quiz?
Honestly, it's not that great (but that's okay, that's how we learn). Here's why:
1) calcu and calcu2 have horrible names. I don't know what they do without looking at the code. They could also be combined since they essentially exist to serve the same purpose.
2) The logic you're using in main() isn't obvious. It really needs a good comment.
3) Your program produces the wrong result when the user enters 2.
4) You don't need to test for user == 9 since this should be covered by calcu2().
When I run this code:
And I write a decimal number, it runs infinite times.
Thanks from Spain,
teacher
Hi Weckersduffer!
A quick recap of for-loops:
A for-loop consits of three parts: for (p1;p2;p3)
p1: This will be executed only one time before the loop starts.
p2: This will be executed every time before the loop cycles. If this is true, the loop will run, if it's false the loop will stop.
p3: This will be executed after every loop cycle.
You are setting y to 5 right before the loop starts.
Then you are checking if y is bigger than 4, which it is, because it's 5.
Now your code inside the loop is executed, but y remains at 5.
After your code has been executed, y will be increased by 1, now y is 6, which still is bigger than 4.
What I'm trying to say is, you're increasing y but never decreasing it. All you're checking is if y is bigger than a certain value. This is what's causing the loop to run for an infinite amount of cycles.
(It's not actually infinite it will stop at some point, you shouldn't worry about it just yet)
I'd like to tell you what you need to change to make your code work, but I don't know what you are trying to do.
Thanks for the answer, nascardriver.
What I was trying to do was the code to run infinite times. So I write an integer, I obtain the answer, and then the code starts again, so I can repeat the process. This way, if I want to enter more than one number, I don´t have to press "F9" each time.
Merry Christmas
In that case you can use a while loop
Output:
More about loops in chapter 5.5 onward.
There are two issues here.
1) Your program runs infinite times no matter what.
2) When you write a decimal number, that's invalid input for an integer. std::cin goes into "failure mode". I talk about how to address such issues in lesson 5.10.
main.cpp
user_cred.cpp
verify.cpp
verify.h
Sir, Why this is not printing "Authenticated" or "Unauthenticated"...?
(Scope.) verifyAuth() cannot access the values assigned from main() because you didn't pass any arguments to the function - like: "verifyAuth(acc, pin)".
These are where your problem areas are:
line 12 in main.cpp
line 5 of verify.h
line 3 of verify.cpp
line 5 of verify.cpp
Good luck!
Dear teacher, please let me ask your judge on following answer to your quiz.
Regards.
Looks fine to me.
Dear Teacher, could you please add << std::endl in snippet
Also in (last) snippet
Regards.