2

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

Chirality
  • 745
  • 8
  • 22

1 Answers1

3

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;
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Lundin
  • 195,001
  • 40
  • 254
  • 396
  • `static inline int32_t circle_area(double r) { return r * r * M_PI; }`? – Jonathan Leffler Apr 05 '16 at 06:59
  • @JonathanLeffler That might force the calculation to be done in runtime, I believe. – Lundin Apr 05 '16 at 07:00
  • Is this possible with constant strings? – Chirality Apr 05 '16 at 07:00
  • @user10984587 Yes, indeed. Which allows you to do various fun tricks at compile-time, for example things [like this](http://stackoverflow.com/a/31051026/584518). – Lundin Apr 05 '16 at 07:03
  • 1
    GCC 5.3.0 on Mac OS X 10.11.4. Source: `int main(void) { int32_t area1 = CIRCLE_AREA(5); int32_t area2 = circle_area(5); printf("%d vs %d\n", area1, area2); return 0; }` — assembler output (most relevant bit): `movl $78, %edx` – `movl $78, %esi` – `leaq LC0(%rip), %rdi` – `xorl %eax, %eax` – `call _printf` — That looks to me as though both function and macro were expanded to 78 by the compiler. – Jonathan Leffler Apr 05 '16 at 07:07
  • 1
    @Lundin under the as-if rule anything that doesn't depend on external input can be done at compile-time. Also the standard does not require that your code happen at compile-time. We are really discussing the expected behaviour of common compilers. – M.M Apr 05 '16 at 08:04
  • The difference is that calling a function is a "side effect", as specified by the rules for the "abstract machine". Which is why I think that the inline function might not be executed at compile time, because calling it would be a side effect. I'm not certain how aggressively a compiler is allowed to optimize away functions without breaking the rules of the abstract machine. – Lundin Apr 05 '16 at 13:14