Side topic: Didn't we have a is_const_eval equivalent in C? I seem to remember a dark magic macro doing precisely that on the lkml somewhere, but can't find it.
You might be able to do something truly arcane using GCC extensions and maybe the __attribute((error))__ thing but realistically it either won't compile or you won't notice unless it's too slow.
The compiler constant folds fairly effectively anyway.
There is no compilation-time evaluation of functions and statements in C. You have constants, which can be expressions, but that's about it. Oh, and macros of course.
compile-time evaluation was introduced in C++11 and expanded in subsequent versions of the language standard.
Also, `const` values in C are not really evaluated at compile time, because they have by default external linkage so they are not really "constant", they are more like "readonly" or 'let' in Rust. They are always loaded from memory, and that's why #define is still king in C.
Doing
const int X = 33;
// ...
void something() {
int arr[X] = ...
}
works in both C and C++, but with a catch: in C++, X is evaluated at compile time (it has internal linkage), while in C this works only after C99 because it's actually a VLA.
What do you want to use it for? C++ uses it for the compile-time programming together with templates. Essentially C++ evolves into a language where you write a program that gets interpreted at compile-time to produce some code that then gets compiled. But I am not sure this is a good idea. It adds a lot of complexity, places many responsibilities that belongs into a compiler onto library writers, increases compilation time a lot, and - with all template expansion - causes a lot of bloat that hurts performance. It also makes debugging interesting. But it looks really good in microbenchmarks because you can create optimal code for special cases easily, I just do not see how this translates into real world performance.
mhh__|3 years ago
The compiler constant folds fairly effectively anyway.
cesarb|3 years ago
It's not exactly the same thing, but it's probably what you were thinking of.
rwmj|3 years ago
pm215|3 years ago
xeeeeeeeeeeenu|3 years ago
Starting with C11, it's possible to implement it without any non-standard extensions: https://stackoverflow.com/a/49480926
einpoklum|3 years ago
compile-time evaluation was introduced in C++11 and expanded in subsequent versions of the language standard.
qalmakka|3 years ago
Doing
works in both C and C++, but with a catch: in C++, X is evaluated at compile time (it has internal linkage), while in C this works only after C99 because it's actually a VLA.esgwpl|3 years ago
uecker|3 years ago
jcelerier|3 years ago