Variables, values, and data types
A variable gives a program a named object whose value can change. Its type tells C++ what category of value the object represents and which operations make sense.
Learning objectives
- Declare and initialize variables using clear names.
- Choose between
int,double,char, andboolfor simple cases. - Distinguish initialization from assignment.
- Trace how an expression updates a variable.
Prerequisites: none. This lesson introduces names, values, and simple C++ types.
Why programs need variables
Programs rarely show only fixed text. A quiz needs a score, a shopping list needs a count, and a temperature monitor needs a measurement. A variable lets the program remember one value under a useful name while it is running.
A labelled container is a useful first analogy: the label tells you what to look for, and the contents may change. It is only an analogy. A C++ object has a type, lifetime, and representation defined by language and implementation rules; do not imagine every variable as a physical box of identical shape.
name: study_minutes type: int current value: 45 name: ready type: bool current value: true
Declare and initialize deliberately
A declaration introduces a name and a type. Initialization gives the object its first value as it is created. In beginner code, initialize every variable you intend to use. Brace initialization is a clear form that also rejects many narrowing conversions.
#include <iostream>
int main() {
int study_minutes{45};
double temperature_celsius{28.5};
char section{'A'};
bool is_ready{true};
study_minutes = study_minutes + 15;
std::cout << "Study minutes: " << study_minutes << '\n';
std::cout << "Temperature: " << temperature_celsius << '\n';
std::cout << "Section: " << section << '\n';
std::cout << "Ready: " << is_ready << '\n';
}Types in this example
| Type | Purpose here | Example value | Important beginner note |
|---|---|---|---|
int | Whole-number count | 45 | Use it for values without a fractional part. Its exact range is implementation-dependent; do not assume a particular number of bits from this lesson. |
double | Floating-point measurement | 28.5 | Useful for many approximate measurements. Most decimal fractions cannot be represented exactly in binary floating point. |
char | One character code unit | 'A' | Single quotes denote one character literal, not a text string. |
bool | Yes/no state | true | Its values are true and false; when printed without formatting, this example commonly displays 1 or 0. |
Code, line by line
- The include line provides the declaration for
std::cout, which the program uses later. int study_minutes{45};creates an integer object namedstudy_minuteswith first value 45.double temperature_celsius{28.5};creates a floating-point object for the decimal measurement.char section{'A'};creates one character object. The single quotes matter.bool is_ready{true};creates a Boolean object.study_minutes = study_minutes + 15;first reads the old value, calculates 45 + 15, then assigns the result, 60, back to the same variable.- Each output statement sends a label and a current variable value to standard output, followed by a newline.
Initialization is not assignment
Initialization happens once, while an object is being created: int score{0};. Assignment changes the value of an object that already exists: score = 10;. Both use value-like syntax, but they answer different questions: “what value does this new object start with?” versus “what value should this existing object have now?”
Execution trace for the update
study_minutes starts as 45 read study_minutes on the right side → 45 calculate 45 + 15 → 60 assign 60 to study_minutes on the left side later output reads study_minutes → 60
The equal sign in an assignment does not ask whether two values are equal. Equality comparison uses ==, which you will study with conditions.
What happens internally
When execution enters main, each declaration creates an automatic object for that function invocation and initializes it. The compiler knows each object’s declared type, so it can diagnose many invalid operations before running. At run time, evaluating the assignment reads the current integer value, performs integer addition, and stores the resulting value back into that object. The exact storage layout and processor instructions are implementation details; the source-level value changes shown in the trace are what matter for learning.
Common beginner mistakes
- Leaving a local fundamental variable uninitialized: write an initial value before reading it. Do not rely on a “default zero” for a local
int. - Using
=when you mean==: assignment changes a value; comparison asks whether values are equal. - Choosing vague names:
total_pricecommunicates more thanx. - Expecting exact decimal arithmetic from
double: it is suitable for many measurements, not automatically for exact currency calculations. - Writing a word in single quotes:
'hello'is not a normal C++ string literal; use double quotes for text. - Silently forcing a decimal into an integer: brace initialization such as
int count{2.5};rejects this narrowing conversion instead of quietly discarding the fractional part.
Practical exercises
- Create variables for your weekly study hours (
int), the room temperature (double), your lab group letter (char), and whether you submitted an assignment (bool). Print them with labels. - Start
pages_readat 12, add 8, then print the result. Draw the execution trace before compiling. - Try
int whole{3.7};. Read the compiler diagnostic, then explain why rejecting the value can prevent a hidden mistake. - Replace one vague variable name in your program with a name that says what the value measures and, where useful, which unit it uses.
- Change
is_readytofalse. Predict what the unformatted output will show, then test it.
Assessment: check your understanding
1. What is a variable in this lesson?
Answer: A named object whose value a program can use and, unless restricted, later change. Why: The name lets later expressions refer to the same program state.
2. What is the difference between int pages{12}; and pages = 20;?
Answer: The first initializes a new object; the second assigns a new value to an existing object. Why: Initialization happens when the object is created, while assignment happens afterward.
3. After int count{4}; count = count + 3;, what is count?
Answer: 7. Why: The right side reads 4 and computes 7; assignment then stores 7 in count.
4. Which type is the best starting choice for a true/false state?
Answer: bool. Why: It directly represents the two Boolean values true and false.
5. Why is int tickets{2.5}; useful as a learning error?
Answer: It rejects a narrowing conversion from a fractional value to an integer. Why: Losing the .5 could hide an unintended change in the data.
Revision summary
Variables hold named program state. A type describes the kind of value and supports compiler checking. Initialize a variable when you create it, use an intentional assignment to change it, and trace the right-hand calculation before it becomes the new left-hand value. Next, you will learn how a program receives values from a user and writes clearer output.
Practice
- Which type is a reasonable choice for a whole-number count?
- What is the difference between
int score{10};andscore = 10;? - Why is
doublenot guaranteed to represent every decimal fraction exactly?
Show reasoned answers
int, when the required range fits its implementation-defined range.- The first declares and initializes a new object; the second assigns a new value to an already-existing object.
- Most decimal fractions have no finite binary representation, so the stored value is an approximation.