C++ Cheatsheet
Basics
Use this C++ reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.
Program Structure
Use this C++ cheatsheet as a fast reference while you learn to code, practice DSA, or prepare for an entry-level software engineer interview where syntax, STL containers, and memory rules need to be automatic.
#include <iostream> // include standard library header #include <string> #include <vector> int main() { // entry point; returns int to OS std::cout << "Hello, World!\n"; return 0; // 0 = success; omittable in main }
Use using namespace std; to avoid std:: prefix (common in competitive programming, avoid in headers).
Fundamental Types
| Type | Size (typical) | Range / Notes |
|---|---|---|
bool | 1 byte | true / false |
char | 1 byte | signed or unsigned, holds one character |
unsigned char | 1 byte | 0–255 |
short | 2 bytes | –32 768 to 32 767 |
int | 4 bytes | –2 147 483 648 to 2 147 483 647 |
unsigned int | 4 bytes | 0 to 4 294 967 295 |
long | 4 or 8 bytes | platform-dependent |
long long | 8 bytes | –9.2×10¹⁸ to 9.2×10¹⁸ |
unsigned long long | 8 bytes | 0 to 1.8×10¹⁹ |
float | 4 bytes | ~7 decimal digits |
double | 8 bytes | ~15 decimal digits |
long double | 12 or 16 bytes | extended precision |
void | — | no type / no value |
Fixed-width types from <cstdint>:
#include <cstdint> int8_t a = -128; uint8_t b = 255; int16_t c; int32_t d; int64_t e; uint16_t f; uint32_t g; uint64_t h;
Variable Declaration and Initialization
int x; // declared, indeterminate (don't read before writing) int y = 10; // copy-initialization int z(10); // direct-initialization int w{10}; // brace (uniform) initialization — preferred (prevents narrowing) int a{}; // zero-initialized: a == 0 double pi{3.14159}; auto n = 42; // type deduced: int auto d = 3.14; // double auto s = std::string{"hello"}; const int MAX = 100; // runtime constant, must be initialized constexpr int SZ = 1 << 10; // compile-time constant
Literals
// Integer 42 // int 42u // unsigned int 42l // long 42ll // long long 42ull // unsigned long long 0xFF // hex: 255 0b1010 // binary (C++14): 10 0777 // octal: 511 1'000'000 // digit separators (C++14) // Floating-point 3.14 // double 3.14f // float 3.14l // long double 1e6 // 1000000.0 (double) // Character 'A' // char L'A' // wchar_t u8'A' // char8_t since C++20 (was char in C++17) u'A' // char16_t U'A' // char32_t // String "hello" // const char[] L"hello" // const wchar_t[] u8"hello" // UTF-8 literal (const char8_t[] since C++20) R"(raw\nstring)" // raw string literal — backslash is literal
Operators
Arithmetic: +, -, *, /, % (modulo, integers only), unary -, unary +
Comparison: ==, !=, <, >, <=, >=
Logical: && (and), || (or), ! (not) — short-circuit evaluated
Bitwise: &, |, ^ (XOR), ~ (NOT), << (left shift), >> (right shift)
Assignment: =, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=
Increment / Decrement: ++x (pre, returns new value), x++ (post, returns old value), --x, x--
Ternary: condition ? expr_if_true : expr_if_false
Comma: a, b — evaluates both, returns right operand (rare outside for)
sizeof: sizeof(int) → 4; sizeof x (no parens for variables)
Operator precedence (highest → lowest, selected):
| Precedence | Operators |
|---|---|
| 1 (highest) | :: |
| 2 | () [] . -> post ++/-- |
| 3 | pre ++/-- ! ~ unary - * & sizeof new delete |
| 5 | * / % |
| 6 | + - |
| 7 | << >> |
| 9 | < <= > >= |
| 10 | == != |
| 11–13 | & ^ | |
| 14 | && |
| 15 | || |
| 16 | ?: |
| 17 | = += -= … |
| 18 (lowest) | , |
When in doubt, use parentheses.
Type Conversions
// Implicit (widening is safe, narrowing may warn/truncate) int i = 3; double d = i; // int → double: fine int j = 3.9; // double → int: truncates to 3 (narrowing, no brace-init) // Explicit casts double x = 3.7; int a = static_cast<int>(x); // preferred C++ cast: 3 char c = static_cast<char>(65); // 'A' // Dangerous casts (avoid unless necessary) int* p = reinterpret_cast<int*>(some_ptr); // bit-level reinterpretation const int ci = 5; int* mp = const_cast<int*>(&ci); // removes const (UB to write) // C-style cast (avoid — does not distinguish intent) int b = (int)x;
Scope, Linkage, and Storage Duration
int global = 1; // namespace scope, static storage, external linkage static int file_only = 2; // internal linkage (visible only in this TU) void f() { int local = 3; // block scope, automatic storage static int count = 0; // local static: persists across calls, init once ++count; } namespace MyNS { int val = 10; // accessed as MyNS::val } extern int other; // declaration only — defined elsewhere
auto, decltype, and Type Aliases
auto x = 42; // int auto& r = x; // int& const auto cx = x; // const int decltype(x) y = 0; // y is int (same type as x) decltype(x + 0.0) z; // z is double // Type aliases using Vec = std::vector<int>; // preferred (C++11) typedef std::vector<int> Vec2; // old style template<typename T> using Pair = std::pair<T, T>; // alias template
Preprocessor Directives
#include <header> // system header #include "myheader.h" // local header #define PI 3.14159 // macro constant (prefer constexpr) #define SQ(x) ((x)*(x)) // macro function (prefer inline or template) #undef PI #ifdef NDEBUG // if macro is defined #endif #ifndef GUARD_H // header guard pattern #define GUARD_H // ... header contents ... #endif #pragma once // non-standard but universally supported header guard #if defined(__cplusplus) && __cplusplus >= 201703L // C++17 or later #endif
Namespaces
namespace Geom { struct Point { double x, y; }; double dist(Point a, Point b); } // Definition outside namespace double Geom::dist(Geom::Point a, Geom::Point b) { /* ... */ } // Using declarations using Geom::Point; // bring one name in using namespace Geom; // bring all in (avoid in headers) // Anonymous namespace — internal linkage (replaces file-static) namespace { void helper() {} } // Inline namespace (C++11) — members visible in enclosing namespace namespace Lib { inline namespace v2 { struct Widget {}; } } Lib::Widget w; // works
Common Gotchas
- Uninitialized variables — reading them is undefined behavior (UB).
- Integer overflow — signed overflow is UB; use
unsignedorlong long. - Narrowing in brace-init —
int x{3.5};is a compile error, which is the point. int / int— integer division:5 / 2 == 2. Cast one operand to get2.5.- Operator precedence —
&<==; write(a & b) == 0, nota & b == 0. =vs==— assignment in a condition compiles but warns; enable-Wall.