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#
| Type | Range | Use for |
|---|---|---|
int | about ±2.1 × 10^9 | everyday counting |
long long | about ±9.2 × 10^18 | sums, products, anything large |
double | about 15 significant digits | measurements, 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#
intoverflows near 2.1 billion; uselong long, and1LL *for products.autoinfers a type;constforbids changes.c - '0'andc - 'a'turn characters into numbers.- Integer
/drops the fraction;static_castconverts explicitly.
Next: operators, and reading input with cin.