
Think of a variable as a labelled box. You put a value in, then use its name later. int means it holds a whole number.
ON THIS PAGE
//THE EXAMPLE
#include <iostream>
using namespace std;
int main() {
int age = 14;
int next = age + 1;
cout << "Now: " << age << endl;
cout << "Next year: " << next << endl;
age = 20; // the box can be refilled
cout << "Later: " << age << endl;
return 0;
}Now: 14 Next year: 15 Later: 20
//LINE BY LINE
Watch it run
int age = 14; makes a box called age and writes 14 into it.
Three ways to give a starting value
C++ has more than one spelling for giving a variable its first value. All three do the same thing here, but the brace form is the safest.
int a = 5; // тэнцүүгээр
int b (5); // хаалтаар
int b2 { 5 }; // буржгар хаалтаар — хамгийн найдвартайWhy is the brace form safest? Because if information would be lost, the compiler refuses instead of quietly rounding.
int x = 3.9; // чимээгүй 3 болно — алдаа мэдэгдэхгүй
int y { 3.9 }; // компилятор алдаа заана — сайн!A variable you never initialise holds whatever junk was in that memory. Declaring int n; and printing it straight away can show any number at all.
Values that must not change (const)
If a value must never change, mark it const. If you later try to change it by accident, the compiler stops you.
const double PI = 3.14159;
const int MAX_STUDENTS = 30;
PI = 3; // ✗ компиляцын алдаа — сайн хэрэгTurning "magic numbers" (30, 3.14) into named const values makes code easier to read and to change later.
Where a variable lives
A variable lives inside the braces where it was declared. When those braces close, it is gone. This is called its scope.
int main() {
int outside = 1;
{
int inside = 2;
cout << outside; // ✓ харагдана
}
cout << inside; // ✗ алдаа — inside аль хэдийн устсан
}