Earlier quoted context omitted.
Just like constant expressions, a function run at compile time needs to be pure , which means no globals, no system calls, no I/O, no undefined behavior. Yes, that does constrain it somewhat, but D users have found it to be immensely useful anyway. There's really no comparison with preprocessor macros. All the preprocessor can do is trivial expressions with long values. Not even floating point. > you add a constexpr…
> D users have found it to be immensely useful anyway. I think you're focused on something that D programmers found helpful, rather than focusing squarely on the needs of C programmers. C and D are both good languages. Their use cases can overlap, but frequently don't. >=70% of the code I write for work is C, as I'm an embedded firmware dev. C meets the very particular needs of bare-metal development, a use case that…
That is hardly the only place that has a constant-expression in the grammar. (BTW, D enums can also be floats, and even string literals!) You could use CTFE to initialize const floating point globals. static_assert also takes a constant-expression.
> There's just a boatload of gotchas.
The D community has 17 years experience with it. It remains an indispensable feature.
As for embedding a printf, that has come up. Recall elsewhere I said that only the path through a function has to be pure for CTFE to work, not the whole function?
int sum(int a, int b) {
int s = a + b;
if (!__ctfe) printf("sum is %d\n", s);
return s;
}
__ctfe is a keyword that says "CTFE is executing this function".> If you could use this feature to define huge matrices of floats, that'd be pretty cool!
I use it to statically initialize complicated tables at compile time. Before CTFE, I wrote a separate executable that would emit source code with the array initializer. I like the new way mucho bettero.
If you prefer "hideous hacks" (your words!) I won't take that away from you.