Beginner · First steps: compiling, output, variables and input · topic 3 of 42 · 30 min
Variables, types and constants
Explanation
Why types?
A variable is a name for a piece of memory that holds a value. In C++ every variable has a type, and the type never changes. The type tells the compiler how many bytes to use and which operations make sense. C++ is statically typed: types are checked at compile time, so many mistakes are caught before the program ever runs.
The basic types
| Type | Holds | Example | Typical size |
|---|---|---|---|
| int | whole numbers | int seats = 72; | 4 bytes, about ±2.1 billion |
| long long | big whole numbers | long long views = 9000000000LL; | 8 bytes, about ±9.2 × 10^18 |
| double | decimal numbers | double price = 499.99; | 8 bytes, about 15–16 digits |
| char | one character | char grade = 'A'; | 1 byte |
| bool | true or false | bool paid = true; | 1 byte usually |
| std::string | text | std::string city = "Pune"; | needs #include <string> |
Sizes are "typical" because the C++ standard only sets minimums; on all common desktop compilers today int is 4 bytes and long long is 8. sizeof(type) tells you the size in bytes on your machine.
#include <iostream>
#include <string>
int main() {
int seats = 72;
double fare = 1450.5;
char coach = 'B';
bool confirmed = true;
std::string name = "Asha";
std::cout << name << " coach " << coach << ", seat " << seats
<< ", fare " << fare << ", confirmed " << confirmed << '\n';
}Always initialise
Declaring a variable means creating it: int x;. Initialising means giving it a first value: int x = 5;. A local int that is declared but not initialised holds garbage: whatever bits were in that memory. Reading it is undefined behaviour, which means the C++ rules say nothing about what happens; the program may print random numbers or behave differently each run.
int total; // garbage, do not read it
int count = 0; // copy initialisation
int marks{85}; // brace initialisation
int bad{3.7}; // compile error: braces refuse to lose the .7Integer division and overflow
std::cout << 7 / 2 << '\n'; // 3 (int / int drops the fraction)
std::cout << 7 / 2.0 << '\n'; // 3.5 (one double makes the result double)
std::cout << 7 % 2 << '\n'; // 1 (remainder)
int big = 2'000'000'000; // ' is a digit separator since C++14
long long safe = 1LL * big * 2; // 4000000000, computed in long longConversions (casts)
int total = 7, people = 2;
double each = static_cast<double>(total) / people; // 3.5
int rounded = static_cast<int>(3.99); // 3, the fraction is cut offconst, constexpr and auto
- const int MAX_SEATS = 72; can never be changed after it is set. Trying to change it is a compile error.
- constexpr double GST = 0.18; is a constant the compiler knows at compile time, usable anywhere a fixed value is needed (like an array size).
- auto lets the compiler work out the type from the value: auto n = 5; is int, auto p = 2.5; is double. Use it when the type is obvious or very long.
Common mistakes
- Using = (assign) when you meant == (compare) in a condition.
- Expecting 5 / 2 to be 2.5. With two ints it is 2.
- Reading a variable before giving it a value.
- Storing big money totals or counts in int. Use long long for anything that may pass 2 billion.
Need help?
Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.
Try:
Watch the lesson
Variables, types and constants · 1/7
In this lesson you will store values in variables, and learn why every variable has a type.
Prefer a video by a teacher? Find free videos on “c++ variables data types int double char bool beginners” on YouTube ↗
In real life: UPI transactions in a day
India processes hundreds of millions of UPI payments in a single day, and amounts summed over a month run into lakhs of crores of rupees. A report program that adds these in an int would overflow past about 2.1 billion. Payment systems store money as whole paise in a 64-bit integer (long long), never as a double, so rounding never loses a paisa.
#include <iostream>
int main() {
long long paise = 0;
paise += 49999; // Rs 499.99
paise += 120000; // Rs 1200.00
std::cout << "Total: Rs " << paise / 100 << "." << paise % 100 << '\n';
}Practice (0/4 done)
Which type is best for storing whether a student has paid the fee?
What does this print? int a = 9, b = 2; std::cout << a / b << " " << a % b;
int x = 50000, y = 50000; long long z = x * y; What is wrong?
Write a program for a canteen: store the price of a thali (double), the number of students (int) and a const GST rate of 5%. Print the total with GST. Then print the average bill per student when 7 rupees of tip is shared between 2 friends, making sure the answer is 3.5 and not 3.
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Reading input and formatting outputFirst steps: compiling, output, variables and input · same module
- Types and variablesC# and .NET · Getting started with C# and .NET
- Variables, basic types and zero valuesGo Programming (backend and cloud) · Getting started with Go
- Type conversion and castingC Programming (from zero to systems) · Operators and control flow
- Your first Dart program, variables and typesFlutter and Dart · Dart basics
- auto, structured bindings and other C++17 conveniencesModern C++: lambdas, C++17 and C++20 essentials
Questions people ask about this
Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.
What is in an int variable declared inside main with int n; and no value?
Answer: Garbage: reading it is undefined behaviour
Local variables are not set to zero automatically. Always initialise them.
What is static_cast<int>(9.99)?
Answer: 9
Converting a double to an int cuts off the fraction; it does not round.
Which line fails to compile?
Answer: int c{3.7};
Brace initialisation forbids narrowing: putting 3.7 into an int would lose data, so it is an error.
Which type should store the population of India (about 1.4 billion) multiplied by 10?
Answer: long long
14 billion is beyond the int range (about 2.1 billion), so use long long.
auto x = 10 / 4; What is x?
Answer: 2 (int)
10 / 4 is int division, giving 2, so auto makes x an int.
Which type holds true or false?Related
Which type is another name for int32 and holds one Unicode character?Related
Answer: rune
rune is an alias for int32 and represents a Unicode code point.
In char a = 100, b = 100; int c = a + b; what is c?Related
What does int.tryParse('x9') return?Related
Answer: null
tryParse returns null for invalid text.
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.
Next steps
- 1 more topic in “First steps: compiling, output, variables and input” before its exam: Reading input and formatting output.
- Module 1 exam: First steps · 12 questions · 20 min, without help. 4 topics of this module still to finish first.
- Then the next module, Decisions, loops and functions. 42 topics left in the course before the final exam.