Core Syntax

Core Syntax

Variables, types, operators, expressions, and declarations at a glance.

Core Syntax

Basic program shape

#include <iostream>

int main() {
    std::cout << "Hello, C++\n";
    return 0;
}

Common fundamental types

Variables and initialization

int a = 1;          // copy initialization
int b(2);           // direct initialization
int c{3};           // brace initialization
const int d = 4;    // immutable
constexpr int e = 5; // compile-time constant
auto name = std::string{"Ada"};

References and qualifiers

int value = 10;
int& ref = value;          // lvalue reference
const int& cref = value;   // read-only reference
int&& rref = 42;           // rvalue reference

Operators

int total = price * count;
bool ready = total > 0 && connected;
auto label = ready ? "ok" : "pending";

These are not just symbols to memorize. They are the core vocabulary for state updates, branching, and object access.

Casts

double x = 3.9;
int i = static_cast<int>(x);
Base* base = dynamic_cast<Base*>(ptr);
const char* raw = reinterpret_cast<const char*>(buffer);

Prefer the narrowest cast that expresses the intended boundary.

Namespaces and aliases

namespace math {
    int square(int x) { return x * x; }
}

using Index = std::size_t;
namespace fs = std::filesystem;

Aliases help when a type or namespace is verbose, but keep them local enough that readers can still tell what they refer to.

Best-practice reminders

auto, decltype, and deduction

std::vector<int> values{1, 2, 3};
auto it = values.begin();          // iterator type deduced
decltype(values.size()) count = values.size();
const int value = 42;
auto copy = value;   // int
auto& ref = value;   // const int&

This is one of the first deduction rules worth remembering because it affects mutation and copying.

Useful modern keywords and attributes

[[nodiscard]] int parse(std::string_view text);
constinit inline int global_counter = 0;

consteval int version() {
    return 23;
}

Comparison and aggregate improvements

struct Point {
    int x{};
    int y{};
    auto operator<=>(const Point&) const = default;
};

Point p{.x = 3, .y = 4};

Declaration vocabulary to remember

Understanding those terms makes later topics such as templates, move semantics, and linkage errors much easier to reason about.

Translation units and headers

#include <vector>
#include "widget.hpp"

Operator groups that matter in real code

Syntax habits worth keeping

Example in practice

int main() {
    int count{3};
    if (count > 0) {
        return count;
    }
    return 0;
}

Try this variation

Refactor the example into a named helper with a single responsibility. If the logic gets easier to test, the design probably improved.

bool is_even(int value) {
    return value % 2 == 0;
}

int main() {
    return is_even(4) ? 0 : 1;
}