Skip to content
Laviyx Learn

Try

C++ Basics Cheat Sheet

Types, operators, input and output, strings, conditions, loops, and functions at a glance.

Updated

Program structure#

C++
#include <iostream>     // std::cout, std::cin
#include <string>       // std::string

int main() {
    std::cout << "Hello, C++!\n";
    return 0;           // optional in main
}
Terminal
g++ -std=c++20 -Wall -Wextra main.cpp -o app
./app

Types and variables#

C++
int count = 42;              // whole number (usually 32-bit)
long long big = 9'000'000'000LL;
double price = 49.99;        // decimal (prefer over float)
char grade = 'A';            // one character, single quotes
bool ok = true;              // true / false
std::string name = "Asha";   // text, double quotes
auto total = price * count;  // type deduced: double

const double tax = 0.18;     // cannot change
constexpr int days = 7;      // compile-time constant

Operators#

KindOperators
Arithmetic+ - * / (integer division for ints) % (remainder, ints only)
Assignment= += -= *= /= %=
Increment++i (new value) i++ (old value) --i i--
Comparison== != < > <= >=
Logical&& || ! (short-circuit)
Conditionalcond ? a : b
C++
7 / 2;                        // 3   (int / int)
7.0 / 2;                      // 3.5
7 % 2;                        // 1
static_cast<double>(7) / 2;   // 3.5
std::pow(2, 10);              // 1024 (from <cmath>, returns double)

Conversions#

C++
int n = std::stoi("42");               // string -> int
double d = std::stod("3.75");          // string -> double
std::string s = std::to_string(99);    // number -> string
int rounded = static_cast<int>(std::round(4.6));   // 5
int digit = '7' - '0';                 // 7

Input and output#

C++
int age = 0;
std::cin >> age;                          // read a number (one word)

std::string line;
std::getline(std::cin >> std::ws, line);  // read a whole line after >>

std::cout << "Age: " << age << '\n';      // '\n' rather than std::endl
std::cout << std::fixed << std::setprecision(2) << 3.14159;   // 3.14 (<iomanip>)
std::cout << std::boolalpha << true;      // true instead of 1

Strings#

C++
std::string s = "Hello";
s.size();                  // 5
s[0];                      // 'H'
s += ", C++";              // "Hello, C++"
s.substr(0, 5);            // "Hello"
s.find("C++");             // 7, or std::string::npos if missing
s.replace(0, 5, "Hi");     // "Hi, C++"
s.empty();                 // false
s.starts_with("Hi");       // true (C++20)

Conditions#

C++
if (score >= 90) {
    grade = 'A';
} else if (score >= 75) {
    grade = 'B';
} else {
    grade = 'C';
}

switch (day) {             // integers, chars, enums only
    case 6:
    case 7:
        std::cout << "weekend\n";
        break;             // don't forget break
    default:
        std::cout << "weekday\n";
}

Loops#

C++
for (int i = 0; i < 5; ++i) { }           // 0, 1, 2, 3, 4

for (const auto& item : items) { }        // each element, no copies
for (auto& item : items) { item *= 2; }   // modify in place

while (balance < target) { }              // check first

do { } while (choice != 0);               // runs at least once

break;      // leave the loop
continue;   // skip to the next iteration

Functions#

C++
int square(int n) {                       // by value: a copy
    return n * n;
}

void add_bonus(double& salary) {          // by reference: can change it
    salary += 5000;
}

double average(const std::vector<int>& v);       // read big objects without copying
void greet(const std::string& name, int times = 1);   // default argument

int area(int side);                       // overloads: same name,
int area(int width, int height);          // different parameters

Common compiler errors#

MessageUsual cause
expected ';' before ...missing semicolon on the line above
'x' was not declared in this scopetypo, missing #include, or variable used outside its block
no match for 'operator<<'printing a type without operator<<
cannot convert ... to ...wrong type passed or assigned
undefined reference to ...function declared but never defined (or a file not compiled)

Want the full explanations? Go to the Learn C++ course →