Skip to content

Beginner · First steps: compiling, output, variables and input · topic 3 of 42 · 30 min

Variables, types and constants

Explanation

A variable is a named box in memory with a fixed type, such as int for whole numbers, double for decimals, char for one character and bool for true/false. C++ checks types when compiling. Always give variables a starting value, and use const for values that must never change.

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.

Think of it like this: Types are like containers in a kitchen. A steel dabba holds dal, a bottle holds water, a salt shaker holds salt. You choose the container before you fill it, and you cannot pour dal into the salt shaker. Once you label a box int, it holds whole numbers for its whole life.

The basic types

TypeHoldsExampleTypical size
intwhole numbersint seats = 72;4 bytes, about ±2.1 billion
long longbig whole numberslong long views = 9000000000LL;8 bytes, about ±9.2 × 10^18
doubledecimal numbersdouble price = 499.99;8 bytes, about 15–16 digits
charone characterchar grade = 'A';1 byte
booltrue or falsebool paid = true;1 byte usually
std::stringtextstd::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.

cpp
#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';
}
Prints Asha coach B, seat 72, fare 1450.5, confirmed 1. A bool prints as 1 or 0 unless you use std::boolalpha.

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.

cpp
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 .7
Brace initialisation {} refuses "narrowing" conversions that would lose data, which catches bugs.

Integer division and overflow

cpp
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 long
When both sides are int, / gives a whole number. Multiply by 1LL first to do the maths in long long.
Careful: Signed integer overflow (going past the largest int) is undefined behaviour in C++. A classic bug: int a = 100000, b = 100000; long long c = a * b; still overflows, because a * b is calculated as int BEFORE it is stored. Write 1LL * a * b or make a and b long long.

Conversions (casts)

cpp
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 off
static_cast<T>(value) is the clear, searchable way to convert. Converting a double to int truncates (drops) the fraction.

const, 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.
Tip: Name variables for what they hold: fare, seatCount, isPaid. Avoid single letters except for loop counters like i. C++ is case sensitive: Fare and fare are different variables.

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

Variables and types

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.

cpp
#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';
}
Prints Total: Rs 1699.99. Money as whole paise in long long avoids both overflow and rounding errors. (For amounts with fewer than 10 paise you would pad with a zero; std::format in a later module does that.)

Practice (0/4 done)

Task 1 · Question

Which type is best for storing whether a student has paid the fee?

Task 2 · Question

What does this print? int a = 9, b = 2; std::cout << a / b << " " << a % b;

Task 3 · Question

int x = 50000, y = 50000; long long z = x * y; What is wrong?

Task 4 · Practice

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

Question 1

1.What is in an int variable declared inside main with int n; and no value?

Question 2

2.What is static_cast<int>(9.99)?

Question 3

3.Which line fails to compile?

Question 4

4.Which type should store the population of India (about 1.4 billion) multiplied by 10?

Question 5

5.auto x = 10 / 4; What is x?

Read more (free)

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

Answer: bool

bool has exactly two values: true and false.

From Types and variables

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.

From Variables, basic types and zero values

In char a = 100, b = 100; int c = a + b; what is c?Related

Answer: 200

Promotion to int prevents overflow in the addition.

From Type conversion and casting

What does int.tryParse('x9') return?Related

Answer: null

tryParse returns null for invalid text.

From Your first Dart program, variables and types

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. 1 more topic in “First steps: compiling, output, variables and input” before its exam: Reading input and formatting output.
  2. Module 1 exam: First steps · 12 questions · 20 min, without help. 4 topics of this module still to finish first.
  3. Then the next module, Decisions, loops and functions. 42 topics left in the course before the final exam.

← Previous: Your first program: main, cout and namespaces