Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

C/C++ compilers will do this when optimization is enabled (I guess the reason that's not done without optimization is to preserve "debuggability").

Notice how the add() function is completely 'disolved' into its result '5' here:

https://www.godbolt.org/z/q98svvacW

(the main difference to comptime is that this guarantees that the code is resolved at compile time, and if that's not possible you'll get an error).

The big downside of comptime is that it isn't debuggable, apart from what's essentially 'printf debugging' via the @compileError builtin).



Graal's native-image tool also does a form of this. The compiler actually executes parts of your program at compile time, but it's real execution so you can theoretically do anything. The heap data that's generated is then persisted into the program. You can debug such code just like normal code by just running it on HotSpot instead.


Not only the work of the C/C++ optimizer but the exact reason why C++ constexpr was designed - to compute expressions during the compile-time iff all its dependants can be resolved during the compile time. If they don't it's still cool, they behave as a normal runtime function.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: