Post

Compile-Time and Runtime in C++

Compile-Time and Runtime in C++

Compile-Time vs Runtime in C++


Prerequisites

1
2
- Compile
- Runtime

1. What is difference between Compile-Time vs Runtime in C++

In C++, operations can be executed at either:

  • Compile-time โ†’ before the program runs
  • Runtime โ†’ while the program is running

๐Ÿ‘‰ Understanding this difference is critical for performance, safety, and optimization

  1. Is this computed at compile-time or runtime?
  2. If runtime โ†’ can it be moved to compile-time?

Move as much work as possible to compile-time for better performance

CategoryCompile-TimeRuntime
TimingBefore executionDuring execution
PerformanceFasterSlower
FlexibilityLess flexibleMore flexible
SafetyHighDepends

2. Compile-Time

Computed during compilation, no runtime cost

๐Ÿ”น constexpr

1
2
3
4
constexpr int square(int x) 
{
    return x * x;
}

Evaluated at compile-time if inputs are known

๐Ÿ”น const

1
const int x = 10;

Compile-time only if initialized with constant expression. If assigned from function โ†’ runtime

๐Ÿ”น consteval (C++20)

1
2
3
4
consteval int square(int x) 
{
    return x * x;
}

Must be evaluated at compile-time

๐Ÿ”น constinit (C++20)

1
constinit int x = 10;

Ensures static initialization at compile-time

๐Ÿ”น Template

1
2
3
4
5
template<int N>
struct Square 
{
    static constexpr int value = N * N;
};

Fully compile-time computation

๐Ÿ”น inline

Suggests compile-time expansion (not guaranteed)

๐Ÿ”น Macro

1
#define SQUARE(x) ((x)*(x))

Preprocessor substitution (before compilation)

๐Ÿ”น static_assert

1
static_assert(sizeof(int) == 4);

Compile-time validation

๐Ÿ”น enum

1
enum { SIZE = 10 };

Compile-time constant

๐Ÿ”น sizeof

1
sizeof(int);

Always compile-time

๐Ÿ”น Array size

1
int arr[10];

Must be known at compile-time

๐Ÿ”น typeid

1
typeid(int);

Compile-time (non-polymorphic types)

3. RunTime

Computed during program execution

๐Ÿ”น Dynamic allocation

1
int* p = new int(10);

๐Ÿ”น Virtual function

1
2
3
4
5
class Base 
{
public:
    virtual void foo() {}
};

Resolved via vtable at runtime

๐Ÿ”น std::function

1
std::function<int(int)> f = [](int x){ return x * x; };

Type-erased, runtime overhead

๐Ÿ”น Async / Thread

1
2
std::async(...);
std::thread(...);

๐Ÿ”น dynamic_cast

1
dynamic_cast<Derived*>(basePtr);

Runtime type checking (RTTI)

๐Ÿ”น reinterpret_cast

1
reinterpret_cast<int*>(ptr);

Unsafe, runtime reinterpretation

๐Ÿ”น unknown function

1
int x = getValue(); // unknown at compile-time
This post is licensed under CC BY 4.0 by the author.