CodeBlanks Logo Icon CodeBlanks

Optimization

Learn compiler optimizations.

Optimization

Optimization is the compiler transforming generated code to be faster or smaller. In GCC and Clang, the -O1, -O2, -O3 flags set the level; -O0 disables optimization (for debugging).

Common optimizations: constant folding (compute constant expressions at compile time), dead code elimination (remove unused code), inlining (put a function body in place of a call), loop unrolling (expand a loop to reduce iteration count). Optimization lengthens compile time but speeds up run time.

Constant folding

Constant folding is the compiler computing constant expressions at compile time. Example: when you write constexpr int a = 5; constexpr int b = a * 2;, the compiler computes b as 10 at compile time; the executable has b directly as 10.

This optimization speeds up the program; the computation finishes at compile time. The constexpr keyword gives this guarantee: the compiler computes these values at compile time. There is no run-time read of a; only the b constant is used.

Practice Write a constexpr constant folding example

Define constexpr int a = 5; and constexpr int b = a * 2;. In main write std::cout << b;.

Starter code

main.cpp
#include <iostream>

// Define the a and b constexpr constants here

int main() {
    // Print b
    return 0;
}

Sample solution

main.cpp
#include <iostream>

constexpr int a = 5;
constexpr int b = a * 2;

int main() {
    std::cout << b;
    return 0;
}

Expected output

10

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the array size

Question
int data[____] = {1, 2, 3};
Answer
int data[3] = {1, 2, 3};

Explanation: For a three-element array, [3].

2 Match each flag to its level

Term Meaning
-O0 No optimization
-O1 Basic optimization
-O2 Standard optimization
-O3 Aggressive optimization

3 Which optimization folds `int x = 2 * 3;` into `int x = 6;`?

main.cpp
int x = 2 * 3;  // computable at compile time
  • Constant folding Correct answer
  • Loop unrolling
  • Inlining
  • Vectorization

Explanation: Constant folding computes constant expressions at compile time.

All lessons in Expert