blog.dopana

Back

Second post in the basic C++ series. Data lives in variables, and every variable has a type that tells the compiler how to interpret its bits.

What is a variable?#

A variable is a named piece of memory that holds a value. You must declare its type before using it:

int age = 30;
double price = 19.99;
std::string name = "Ada";
bool done = false;
cpp

Fundamental data types#

TypeSize (typical)What it holds
bool1 bytetrue or false
char1 byteone character, e.g. 'A'
int4 byteswhole numbers
double8 bytesfloating-point numbers
voidno value (for functions)

Use int for counts and double for fractional values. Use long, short, and unsigned when you need a different range.

Initialization styles#

C++ offers several ways to initialize a variable:

int a = 5;       // copy initialization
int b(5);        // direct initialization
int c{5};        // brace initialization (C++11+)
int d{};         // value-initialized to 0
cpp

Prefer brace initialization {}. It rejects narrowing conversions — a value that would lose data — at compile time.

Overflow and narrowing#

short s = 40000;  // may overflow: 40000 > max short (32767)
int   x = 3.7;    // narrowing: 3.7 silently becomes 3
cpp

With braces these fail to compile instead of silently corrupting data.

Named constants#

Use const for values that must not change:

const double PI = 3.14159;
cpp

const values are easier to reason about and the compiler can optimize them.

Printing and reading#

#include <iostream>

int main() {
    int age;
    std::cout << "Enter your age: ";
    std::cin >> age;
    std::cout << "You are " << age << " years old.\n";
}
cpp

Conclusion#

Types define what a variable can hold and what operations make sense. Next in this series: control flow.

References#