</>CodexBash
C++
C++Beginner10 min

Variables and data types

C++'s number, character and text types, overflow and long long, auto, const, and converting between types safely.

Variables are named boxesstep 1/6
?
age
?
name
?
count
Three variables, not yet given a value. Each is a named box in memory.

Declaring variables#

int age = 21;
double price = 99.5;
char grade = 'A';
bool passed = true;
string name = "Asha";       // #include <string> for this

Every variable has a fixed type. Always give a starting value: an uninitialised int holds whatever was in that memory.

Number types#

TypeRangeUse for
intabout ±2.1 × 10^9everyday counting
long longabout ±9.2 × 10^18sums, products, anything large
doubleabout 15 significant digitsmeasurements, averages

int stops at 2147483647. Past that the value wraps around silently and your answer is wrong with no error. If values can approach a billion, or you add many together, or multiply two, use long long:

long long total = 0;
for (int x : nums) total += x;       // safe even for 100000 values of 10^9
long long area = 1LL * width * height;   // multiply in 64 bits

1LL * makes the multiplication happen in long long before it can overflow.

auto#

The compiler can work the type out from the value:

auto count = 0;          // int
auto ratio = 0.5;        // double
auto name = string("Asha");

auto shines with long type names you will meet later, such as iterators and pairs. For simple numbers, writing the type is clearer.

const#

const int DAYS = 7;
DAYS = 8;      // error: cannot change a const

Mark values that should never change as const. The compiler then stops you, and anyone reading your code, from changing them by accident.

Characters#

A char is a small number, so character arithmetic works:

char c = '7';
int digit = c - '0';         // 7
int letter = 'd' - 'a';      // 3
char up = toupper('q');      // 'Q', from <cctype>

Single quotes are one character; double quotes are text.

Integer division#

Dividing two integers drops the fraction:

int a = 7, b = 2;
double wrong = a / b;                       // 3
double right = static_cast<double>(a) / b;  // 3.5

static_cast<double>(a) is the C++ way to convert explicitly. It is longer than C's (double) a, on purpose: conversions are easy to find and hard to write by accident.

Floating point is approximate#

0.1 + 0.2 is not exactly 0.3 in any language. Compare doubles with a tolerance, abs(x - y) < 1e-9, and prefer whole numbers when the problem allows.

Key points#

  • int overflows near 2.1 billion; use long long, and 1LL * for products.
  • auto infers a type; const forbids changes.
  • c - '0' and c - 'a' turn characters into numbers.
  • Integer / drops the fraction; static_cast converts explicitly.

Next: operators, and reading input with cin.

Practise it

The same idea, in the order it is worth meeting it.

  1. Not startedHow many digitsEasy
  2. Not startedTurn the digits aroundEasy
Create a free account to track your progress