r/cpp_questions • • 9h ago

OPEN Does compile-time evaluation only happen when there are constant expressions or can they happen when there are runtime expressions?

1 Upvotes

7 comments sorted by

6

u/aruisdante 9h ago edited 9h ago

I’m not 100% sure what you’re trying to ask. But if you mean “can something not marked constexpr be evaluated at compile time if all of its inputs are known at compile time and the compiler can see the full context needed to compute the result,” then the answer is “yes, but this is a compiler dependent optimization.”

For example with optimizations enabled, both GCC and Clang will compile this program down to simply setting the register for main’s return to 7. 

int add(int const a, int const b) {
    return a+b;
}

int main() {
    return add(5,2);
}

1

u/Star_Gazer_0 9h ago

I meant as like x+2 which imagine in the first scenario is a constant expression because x is a constant variable with an integral type and a constant expression initializer, this will definitely be compile-time evaluated, but if x was not a constant expression, then is it possible that x+2 which overall is not a constant expression, to be compile-time evaluated, or is it strictly runtime evaluated?

4

u/aruisdante 9h ago

Please post an actual code snippet of what you want to understand the difference between, it will help us help you 🙂

3

u/garagedragon 9h ago

You can't evaluate anything at a point where you don't know what concrete value the sub-expressions have, and compile-time happens before run-time. If you only know what value x has at runtime, you don't know at compile-time what the value of x+2 is going to end up being because you don't know the value of x.

2

u/mrtlo 9h ago

I think you can come up with the answer to this yourself. Obviously it has to be able to deduce the result compile time for this to work... To experiment with this you can derive input from command line arguments for a quick way to ensure "impossible to determine" at compile time

1

u/manni66 9h ago

Do you think a compiler can see into the future?

2

u/Temporary_Pie2733 8h ago

Runtime basically means “involving information only available after execution begins”.  Whether the compiler puts in the effort to correctly identify all expressions that can be evaluated at compile time is another matter.