Shiklo Tools
PDF40
Image20
Calculators & Converters25
Text & Writing13
Developer26
Video14
Audio14
Document14
Data & Spreadsheet12
Web & SEO9
OCR & Scanning5
Archive & File12
Security & Privacy23
Health & Medical29
QR & Barcode5

C++ Variables and Constants

A variable is a named place in memory that holds a value. Every variable has a type that decides what it can hold: int for whole numbers, double for decimals, char for a character, bool for true or false, std::string for text.

Declaring and initialising

#include <iostream>
#include <string>

int main() {
    int age = 12;
    double height = 1.45;
    char grade = 'A';
    bool passed = true;
    std::string name = "Asha";

    std::cout << name << " is " << age << " years old.\n";
    std::cout << "Height: " << height << " m, grade " << grade << "\n";
    std::cout << "Passed: " << passed << "\n";
    return 0;
}
Output
Asha is 12 years old.
Height: 1.45 m, grade A
Passed: 1

A bool prints as 1 or 0; the next topics show how to print true and false.

Brace initialisation

Modern C++ can also initialise with braces: int count{5};. Braces refuse conversions that lose information, so int n{2.5}; is an error instead of silently cutting off the .5. An empty pair, int total{};, sets the value to zero.

#include <iostream>

int main() {
    int count{5};
    double price{9.99};
    int total{};          // zero
    std::cout << count << " " << price << " " << total << "\n";
    return 0;
}
Output
5 9.99 0

Changing a value

#include <iostream>

int main() {
    int score = 10;
    score = 25;           // replace
    score += 5;           // add to the old value
    std::cout << "Score: " << score << "\n";
    return 0;
}
Output
Score: 30

Constants

const makes a variable that cannot be changed after it gets its value. constexpr goes further: the value must be known when the program is compiled, so the compiler can use it everywhere, even as an array size.

#include <iostream>

int main() {
    constexpr double PI = 3.14159;
    constexpr int DAYS_PER_WEEK = 7;
    const int weeks = 3;
    std::cout << weeks * DAYS_PER_WEEK << " days\n";
    std::cout << "Area of a circle with radius 2: " << PI * 2 * 2 << "\n";
    return 0;
}
Output
21 days
Area of a circle with radius 2: 12.5664

Writing weeks = 4; afterwards is a compile error, which is exactly the point: a value that must not change cannot be changed by mistake.

Naming

  • Letters, digits and underscores, not starting with a digit; case matters.
  • Keywords like int, class or return cannot be names.
  • Choose names that explain the value: studentCount or student_count, not sc.
  • Always give a variable a value when you create it; an uninitialised local variable holds garbage.

Practice exercises

  1. Create variables for your name, age and height and print them in a sentence.
  2. Swap two int variables using a third one.
  3. Try int n{2.5}; and read the error. Then try int n = 2.5; and compare.