Notes
All notes

C/C++ Fundamentals (C++ Core #1)

Most “predict the output” questions are not about algorithms. They are about what the compiler was allowed to do with your code: which declaration the name binds to, when the object dies, which conversion happens silently, and which order the compiler is allowed to choose. This post covers those rules.

From source to executable

Four stages run in order:

  1. Preprocess — expand #include, #define, #if. Output is one big translation unit of pure C++.
  2. Compile — parse and type-check the translation unit, emit assembly.
  3. Assemble — turn assembly into an object file of machine code plus a symbol table.
  4. Link (linking) — combine object files and libraries, resolve symbols, produce the executable.
g++ -E main.cpp -o main.ii     # preprocess only
g++ -S main.cpp -o main.s      # compile to assembly
g++ -c main.cpp -o main.o      # compile + assemble, no link
g++ main.o util.o -o app       # link

The separation matters because most errors are either compile errors (a name is not declared, a type is wrong) or link errors (a symbol is declared and used but never defined). A missing ; is the former; a missing function body is the latter.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, rounded corners=3pt, minimum width=1.7cm, minimum height=0.7cm, font=\scriptsize, align=center},
  a/.style={->, thick}]
  \node[b, fill=blue!10] (s) at (0,0) {main.cpp\\+ headers};
  \node[b, fill=orange!15] (p) at (2.2,0) {preprocessor};
  \node[b, fill=orange!15] (c) at (4.4,0) {compiler};
  \node[b, fill=orange!15] (as) at (6.4,0) {assembler};
  \node[b, fill=green!18] (l) at (8.6,0) {linker};
  \node[b, fill=blue!10] (e) at (10.6,0) {app};
  \foreach \x/\y in {s/p,p/c,c/as,as/l,l/e} \draw[a] (\x) -- (\y);
  \node[font=\scriptsize, text=black!60, anchor=north] at (2.2,-0.55) {main.ii};
  \node[font=\scriptsize, text=black!60, anchor=north] at (4.4,-0.55) {main.s};
  \node[font=\scriptsize, text=black!60, anchor=north] at (6.4,-0.55) {main.o};
\end{tikzpicture}
QQuestionA function is declared in a header, called in main.cpp, and

defined in util.cpp. Which stage complains if util.cpp is not passed to the compiler?

ASolution

The linker. Compilation succeeds because the declaration is enough to type-check the call; the symbol is only resolved at link time.

Preprocessing, headers and translation units

A translation unit (TU) is one .cpp file after preprocessing: the file plus everything it #included. Each TU is compiled independently, so each one needs to see the declarations it uses.

// util.h
#pragma once
int add(int a, int b);      // declaration only

// util.cpp
#include "util.h"
int add(int a, int b) { return a + b; }   // definition

// main.cpp
#include "util.h"
int main() { return add(2, 3); }

Putting a definition in a header is how you get the same function defined in every TU, which the linker rejects as “multiple definition”. The exceptions are inline functions, templates, and constexpr functions, which are allowed in headers because the linker merges their definitions.

#pragma once and header guards both stop a header from being included twice in one TU. They do not stop it from being included in two different TUs — that is fine, because each TU is compiled separately and only declarations are shared.

Preprocessing is textual: #include <vector> literally pastes the contents of the standard header into your file. That is why a missing #include produces “incomplete type” or “not declared” errors at the point of use, not at the top.

QQuestionmain.cpp includes a.h, and a.h includes b.h. How many times

does b.h’s content appear in main.cpp’s translation unit?

ASolution

Once, if it has a guard or #pragma once. Without one, once per inclusion path, which is how circular includes blow up.

Declarations versus definitions

A declaration introduces a name and its type. A definition gives it storage or a body. You can declare many times; you can define once.

extern int x;             // declaration: x exists somewhere
int x = 5;                // definition: storage allocated
int f(int);               // declaration
int f(int a) { return a; }// definition

extern int y = 7;         // extern + initializer is a definition

Functions have no “tentative” rules in C++; a prototype without a body is a declaration, and a body is a definition. In C, int x; at file scope is a tentative definition and becomes a real one at the end of the TU; in C++ it is a definition immediately. That is a favourite C-versus-C++ question.

inline functions and variables are the C++17 way to put a definition in a header:

inline int counter = 0;              // one entity, many TUs
inline int twice(int x) { return 2 * x; }
QQuestionIs class Foo { void bar(); }; a definition of bar?
ASolution

No. It declares bar. The class is defined, but bar needs an out-of-line void Foo::bar() { ... } or an inline body inside the class.

Scope and name lookup

Scope is where a name is visible. Lifetime is when an object exists. They are different, and mixing them up causes dangling references.

int x = 1;
int main() {
    std::cout << x << '\n';   // 1, global
    int x = 2;                // hides the global
    std::cout << x << '\n';   // 2
    {
        int x = 3;
        std::cout << x << '\n'; // 3
    }
    std::cout << x << '\n';   // 2
    std::cout << ::x << '\n'; // 1, qualified
}

Lookup goes outward through enclosing scopes and stops at the first match. A declaration is visible from its point of declaration to the end of its scope, so a name used before its declaration inside the same block does not see it.

int y = 10;
void f() {
    std::cout << y;    // 10 (global)
    int y = 20;        // new variable, from here on
}

Class members, namespaces, and using declarations add layers. For obj.member, lookup starts in the class; for f(x), argument-dependent lookup (ADL) also searches the namespaces of the argument types, which is why std::cout << s finds operator<< without std::.

QQuestionWhat does int x = x; do inside a function?
ASolution

It is undefined behaviour. The initializer’s x refers to the new variable (already declared at that point) and reads it before it is initialized.

Storage duration and object lifetime

Storage duration says how long the storage lasts. Lifetime says when an object exists in that storage. For most types they start and end together; for unions and placement new they do not.

Duration Created Destroyed Example
automatic at declaration end of block local variable
static before main (or first use for locals) after main global, static local
thread at thread start (or first use) at thread exit thread_local
dynamic (heap) new / malloc delete / free heap object
struct S {
    S()  { std::cout << "ctor\n"; }
    ~S() { std::cout << "dtor\n"; }
};
void f() {
    S a;                 // ctor at this line
    static S b;          // ctor on first call, dtor at program exit
    S* c = new S;        // ctor now, dtor only on delete
    delete c;
}                        // a's dtor here

A static local is initialized the first time control reaches its declaration, which is thread-safe since C++11. A namespace-scope static is initialized before main (order across TUs is unspecified — see Ch. 8).

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  a/.style={->, thick}]
  \draw[a] (0,0) -- (9,0) node[right, font=\scriptsize] {time};
  \draw[very thick, blue!60] (0.2,0.55) -- (8.6,0.55);
  \node[font=\scriptsize, text=blue!60!black, anchor=south] at (4.4,0.6) {static / global lifetime};
  \draw[very thick, orange] (2.4,1.15) -- (4.0,1.15);
  \node[font=\scriptsize, text=orange!80!black, anchor=south] at (3.2,1.2) {automatic};
  \draw[very thick, green!45!black] (5.2,1.75) -- (6.6,1.75);
  \node[font=\scriptsize, text=green!45!black, anchor=south] at (5.9,1.8) {heap};
  \draw[dashed] (2.4,0) -- (2.4,1.1);
  \draw[dashed] (4.0,0) -- (4.0,1.1);
\end{tikzpicture}

Scope does not keep an object alive, and lifetime does not depend on scope: new inside a block survives the block, while a local’s storage is gone.

QQuestionWhen is a function-local static object destroyed?
ASolution

At program exit, in reverse order of construction, after main returns. Its lifetime is the whole program, not the function call.

Type conversions and casts

C++ converts types implicitly in many places: assignment, function calls, return statements, arithmetic, and boolean contexts. Some conversions are safe, some lose data, and some are surprising.

double d = 3.9;
int i = d;                 // 3, truncation toward zero
bool b = d;                // true (non-zero)
char c = 'A';
int n = c;                 // 65

unsigned u = -1;           // 4294967295 (mod 2^32)
int back = u;              // implementation-defined if out of range

Arithmetic conversions follow two steps:

  1. Integer promotion: bool, char, short (and their unsigned versions if int can hold all values) promote to int.
  2. Usual arithmetic conversions: the operands of an operator are converted to a common type, with int → long → long long → float → double and unsigned versions mixed in.

The unsigned rule is the trap:

int a = -1;
unsigned b = 1;
std::cout << (a < b);      // 0 (false): a converts to 4294967295

Explicit casts, in order of preference:

double d = 3.7;
int i = static_cast<int>(d);          // checked, explicit, intended

const int c = 5;
int* p = const_cast<int*>(&c);        // removes const; writing through p is UB

void* raw = &i;
int* q = static_cast<int*>(raw);      // fine for void*
long addr = reinterpret_cast<long>(&i);  // bit reinterpretation, no conversion

Base* base = new Derived;
Derived* der = dynamic_cast<Derived*>(base);  // checked at runtime, may be null

dynamic_cast needs a polymorphic type (at least one virtual function), because it reads the runtime type information.

Avoid C-style casts (int)x: they try const_cast, static_cast, and reinterpret_cast in that order and hide which one happened.

QQuestionWhy is char c = 300; a problem even though it compiles?
ASolution

300 does not fit in an 8-bit char. The conversion is implementation-defined (usually wraps to 44), and the compiler may warn. Use static_cast and a wider type if the value matters.

Operator precedence and associativity

Precedence decides which operator binds tighter; associativity decides the order for equal precedence. A partial table, tightest first:

Level Operators Associativity
1 :: left
2 () [] . -> ++ -- (postfix) left
3 ! ~ ++ -- + - * & (unary), sizeof, casts right
5 * / % left
6 + - left
7 << >> left
9 < <= > >= left
10 == != left
11 & left
12 ^ left
13 bitwise OR left
14 && left
15 logical OR left
16 ?: right
17 = and compound assignments right
18 , left

Two classic misreads:

int a = 2, b = 3;
if (a & b == 0) { }        // parsed as a & (b == 0) → 2 & 0 = 0

int x = 1 << 2 + 3;        // 1 << (2 + 3) = 32, not (1 << 2) + 3 = 7

*p++ is *(p++), because postfix ++ binds tighter than unary *. (*p)++ increments the pointee.

QQuestionWhat does a = b = c do, and in which direction?
ASolution

Assignment is right-associative, so it is a = (b = c): c is assigned to b, and the value of that assignment is assigned to a.

Evaluation order

Order of evaluation is where “it worked on my machine” stops being an argument. C++17 fixed some of this, and the differences are exactly what exams test.

Guaranteed sequenced-before relationships (C++17):

Expression Guarantee
a && b, logical OR a before b (short-circuit)
a ? b : c a before b or c
a, b a before b
a[b] a before b
a.b, a->b a before the member
a << b, a >> b a before b
a = b b before a
f(args...) function before arguments; arguments indeterminately sequenced relative to each other
int i = 0;
int x = i++ + i++;     // UB: two unsequenced modifications of i
i = i++;               // UB in every standard, even C++17
int y = i++ + 1;       // fine

int f(), g();
std::cout << f() << g();   // C++17: f() runs first
f(i++, i++);               // C++17: unspecified order, but not UB

Before C++17, f(i++, i++) was undefined; C++17 made function arguments indeterminately sequenced, which means one argument is evaluated completely before the other, but which one is unspecified. That is a real distinction: unspecified gives a valid program with more than one possible answer; undefined gives no guarantees at all.

Short-circuit evaluation is part of the language, not an optimization:

if (p != nullptr && p->value > 0) { }   // safe: p->value not evaluated if p is null

Swap the operands and the null check no longer protects anything.

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, rounded corners=3pt, minimum width=2.4cm, minimum height=0.62cm, font=\scriptsize},
  a/.style={->, thick}]
  \node[b, fill=blue!10] (l) at (0,1.5) {left operand};
  \node[b, fill=orange!15] (r) at (3.4,1.5) {right operand};
  \draw[a] (l) -- node[above, font=\scriptsize] {must finish first} (r);
  \node[font=\scriptsize, anchor=north] at (1.7,0.75) {logical and/or, comma, shift, assignment};
  \node[b, fill=gray!12] (x) at (0,-0.2) {argument A};
  \node[b, fill=gray!12] (y) at (3.4,-0.2) {argument B};
  \node[font=\scriptsize, anchor=north] at (1.7,-0.9) {function arguments: order unspecified};
\end{tikzpicture}
QQuestionstd::cout << i++ << i++; — is the output defined in C++17?
ASolution

Yes. Chained << is (cout << i++) << i++, and C++17 sequences the left operand of << before the right one, so it prints 0 then 1. Before C++17 it was undefined. i++ + i++ is still undefined, because + does not sequence its operands.

Bugs and edge cases

QQuestionint a[10]; std::cout << sizeof(a) / sizeof(a[0]); inside main

prints 10. What does the same expression print inside a function taking int a[]?

ASolution

2 on a 64-bit machine, because the parameter is a pointer (8 bytes) and sizeof(a[0]) is 4. The array size was lost at the call.

Next: Pointers and References (C++ Core #2) — const forms, decay, and what sizeof really measures.