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
- Is this computed at compile-time or runtime?
- If runtime โ can it be moved to compile-time?
Move as much work as possible to compile-time for better performance
| Category | Compile-Time | Runtime |
|---|---|---|
| Timing | Before execution | During execution |
| Performance | Faster | Slower |
| Flexibility | Less flexible | More flexible |
| Safety | High | Depends |
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