Declaring variables
- C++ course
- Beginner
- Lesson 7/116
- 4 min
Learn to declare variables of type int, double, char, bool and float.
Declaring variables
A variable is a box that holds a value by name. In C++ you declare a variable by writing its type, then its name, then an optional initial value: int score = 90;.
Common types: int (integer), double (floating-point), float (single-precision decimal), char (single character) and bool (true/false).
A variable name must start with a letter or underscore and contain no spaces. English letters are recommended for portability.
Initialization
Giving a variable a value when it is declared is called initialization. int x = 5; sets x to 5. int x; leaves x uninitialized; reading it before assigning causes undefined behavior.
Three initialization forms are common in C++:
int x = 5;— copy initializationint x{5};— brace initialization (prevents narrowing)int x(5);— parenthesis initialization
Initialization adds safety and predictability; always assign a value before reading a variable.
Practice Declare four types and print
Inside main, declare an int, a double, a char and a bool variable with the values 90, 19.99, 'A' and true respectively. Print each on its own std::cout line using std::endl.
Starter code
#include <iostream>
int main() {
// Declare an int, a double, a char and a bool
// Print each with std::cout
return 0;
}Sample solution
#include <iostream>
int main() {
// Declare an int, a double, a char and a bool
int score = 90;
double price = 19.99;
char grade = 'A';
bool active = true;
// Print each with std::cout
std::cout << score << std::endl;
std::cout << price << std::endl;
std::cout << grade << std::endl;
std::cout << active << std::endl;
return 0;
}Expected output
90 19.99 A 1
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which is a valid variable declaration?
- int 2count = 5;
- int count = 5; Correct answer
- int count = ;
- int = 5;
Explanation: int count = 5; is a valid declaration.
2 Floating-point variable
____ price = 19.99;
double price = 19.99;
Explanation: double is used for floating-point values.
3 Match types with examples
| Term | Meaning |
|---|---|
int |
90 |
double |
19.99 |
char |
'A' |
bool |
true |