bool and char
- C++ course
- Beginner
- Lesson 15/116
- 3 min
Learn to store logical values with bool and characters with char.
bool and char
The bool type takes only two values: true (1) and false (0). It is used in conditions and flags: bool active = true;.
The char type holds a single character: char grade = 'A';. Characters are written in single quotes. A char is actually a small integer; each character has a number in the ASCII table.
When printing a bool, std::cout shows 1 or 0; to print true/false use std::boolalpha.
char and numbers
Each char maps to a number: 'A' = 65, 'B' = 66, 'a' = 97, '0' = 48. So writing char c = 65; and then std::cout << c; prints A.
This lets you do arithmetic between characters: 'A' + 1 gives 'B'. It is handy for ordering or converting letters.
Conversely, static_cast<int>('A') gives 65. This is how you convert between characters and numbers.
Practice Print bool and char
Inside main, declare a bool (value true) and a char (value 'B'). Print both on separate lines with std::cout using std::endl.
Starter code
#include <iostream>
int main() {
// Declare bool and char
// Print each with std::cout
return 0;
}Sample solution
#include <iostream>
int main() {
// Declare bool and char
bool ready = true;
char grade = 'B';
// Print each with std::cout
std::cout << ready << std::endl;
std::cout << grade << std::endl;
return 0;
}Expected output
1 B
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match types with examples
| Term | Meaning |
|---|---|
bool |
true |
char |
'A' |
true |
1 |
'B' |
66 |
2 What is the output of char c = 65; std::cout << c;?
char c = 65;
std::cout << c;- A Correct answer
- B
- Error
- 65
Explanation: 65 corresponds to the letter 'A' in the ASCII table.
3 Character declaration
____ grade = 'B';
char grade = 'B';
Explanation: char holds a single character.