C++ Basics

Types & auto

C++ is statically typed and compiles straight to machine code — no virtual machine between your program and the CPU. That's the source of both its speed and its sharp edges.

C++20 ✓ Beginner Friendly 2 Topics
01

Fundamental Types & auto

C++ types map directly to memory. An int is a fixed number of bytes the CPU understands natively. auto lets the compiler deduce the type from the initializer, but the type is still fixed at compile time.

C++ — Declarations
#include <iostream>
#include <string>

int main() {
    int age = 25;
    double price = 3.14;
    bool active = true;
    char grade = 'A';
    std::string name = "Alice";

    // auto — compiler deduces the type, still static
    auto x = 10;           // int
    auto pi = 3.14;        // double
    auto greeting = "hi";   // const char*

    // const — a compile-time constant
    const double PI = 3.14159;

    std::cout << name << " is " << age << "\n";
    return 0;
}
Common Fundamental Types
TypeTypical SizeExampleUsed For
int4 bytesint i = 42;Default whole number
long long8 byteslong long l = 9LL;Large integers
double8 bytesdouble d = 1.5;Default decimal
bool1 bytebool ok = true;Conditions
char1 bytechar c = 'A';Single byte / character
std::stringvariesstring s = "hi";Text (from <string>)
Sizes are not guaranteed. The C++ standard only sets minimums — an int is at least 16 bits but usually 32. For fixed widths use <cstdint> types like int32_t and int64_t.
02

const & References

A reference (&) is an alias for an existing variable — another name for the same memory, with no copy made. Combined with const, it's how you pass big objects into functions cheaply and safely.

C++ — References
int x = 10;
int& ref = x;      // ref is an alias for x — same memory
ref = 20;
std::cout << x;    // 20 — changing ref changed x

// const reference — read-only alias, no copy
const int& cref = x;
// cref = 30;      // ERROR — cannot modify through a const ref

// pass a big object by const ref: no copy, cannot mutate
void print(const std::string& s) {
    std::cout << s;   // reads s without copying it
}
Pass-by-const-reference is the C++ default for anything bigger than a couple of bytes. Passing by value copies the whole object; const T& passes a cheap alias and promises not to change it.

Quick Quiz

1. auto x = 10; deduces x as…
2. The size of int in C++ is…
3. int& ref = x; makes ref…
4. Why pass a std::string as const std::string&?
5. C++ compiles to…