C++ ยท Chapter 7 of 49

C++ Variables

A variable is a named storage location with a specific type, and in C++ you must declare its type before use. Once declared, a variable can be assigned and reassigned values matching that type.

Variables can be declared and initialised in one line, or declared first and assigned later. Choosing descriptive names makes code much easier to read.

Declaring variables

Syntax is `type name = value;`, e.g. `int age = 25;`. You can declare multiple variables of the same type on one line separated by commas.

Naming rules

Names can contain letters, digits and underscores but can't start with a digit. C++ reserved keywords like `int` or `return` cannot be used as variable names.

Example 1 (cpp)
int age = 25;
std::cout << age;
Output
25

Declares an int variable and prints it.

Example 2 (cpp)
int a = 1, b = 2;
std::cout << a + b;
Output
3

Multiple variables of the same type declared on one line.

Key points

  • Variables must have a declared type in C++.
  • Syntax: type name = value;
  • Names are case-sensitive and cannot start with a digit.
  • Reassigning a variable keeps its original type.
๐Ÿ’ก Note: Uninitialised local variables contain garbage values โ€” always initialise before use.

๐Ÿ“ Quick Quiz

1. Which is a valid variable declaration?

2. C++ variables:

3. What happens if you don't initialise a local variable?