Chirality
Chirality

Reputation: 745

Compile-Time Function Execution

Is there a way to perform compile-time function execution in C? With GCC? I've only seen this available using constexpr in C++.

Upvotes: 2

Views: 5000

Answers (1)

Lundin
Lundin

Reputation: 215360

As long as there are only constants involved in an expression, it will get calculated at compile-time. C++ constexpr is mostly a type safe way of doing so without involving macros. In C, there are only macros. For example:

#define CIRCLE_AREA(r) (int32_t)( (double)(r) * (double)(r) * M_PI )

int32_t area = CIRCLE_AREA(5);

performs all calculations at compile-time, so it is equivalent to writing:

int32_t area = 78;

Upvotes: 4

Related Questions