C++ Variables

C++ variables store data, and each one has a type that is fixed at compile time. This lesson covers the basic data types, ways to initialize variables, and constants.

Basic C++ Data Types

  • int: whole numbers (usually 4 bytes)
  • double: decimal numbers with ~15 digits precision
  • char: a single character
  • bool: true or false
  • std::string: text (from <string>)
  • long long, float, unsigned: other numeric variants

Declaring Variables

Brace initialization ({}) is the modern style. It also prevents narrowing conversions, such as putting 3.7 into an int.

#include <iostream>
#include <string>

int main() {
    int age{30};
    double height{1.75};
    char initial{'N'};
    bool active{true};
    std::string city{"Lahore"};

    std::cout << age << ' ' << height << ' ' << initial << ' '
              << std::boolalpha << active << ' ' << city << '\n';
}
30 1.75 N true Lahore

The auto Keyword

auto tells the compiler to deduce the type from the initializer. It is handy for long type names.

#include <iostream>

int main() {
    auto count = 10;      // int
    auto ratio = 0.25;    // double
    auto letter = 'z';    // char
    std::cout << count * ratio << ' ' << letter << '\n';
}
2.5 z

const and constexpr

const means the value cannot change after initialization. constexpr goes further: the value must be known at compile time.

#include <iostream>

constexpr double PI = 3.14159;

int main() {
    const int radius = 3;
    std::cout << "Area: " << PI * radius * radius << '\n';
}
Area: 28.2743

Naming Rules

  • Start with a letter or underscore.
  • Use only letters, digits and underscores.
  • Do not use keywords like class or int.
  • Pick clear names such as totalPrice.

Frequently asked questions

When should I use auto in C++?

Use auto when the type is obvious from the right-hand side or very long, such as iterators. Write the type explicitly when it improves readability.

What is the difference between const and constexpr?

const means read-only after initialization, possibly at runtime. constexpr requires a compile-time value, so it can be used for array sizes and template arguments.

Why use braces to initialize variables in C++?

Brace initialization works the same for all types and refuses narrowing conversions, catching bugs like int x{3.7} at compile time.