r/cpp_questions • • 1d ago

OPEN Can runtime expressions(which are not constant expressions) not be optimized (which takes place during compile time)?

5 Upvotes

6 comments sorted by

8

u/dontwantgarbage 1d ago

You can still optimize them. For example, a = (x + 1) * (x + 1); is probably optimized to temp = x + 1; a = temp * temp;

6

u/WorkingReference1127 1d ago

Optimising isn't a process where expressions are evaluated in the traditional sense. It's not like constant expressions. It's a process where your code is effectively rewritten to be more efficient. Your optimiser will, in effect, produce code as if you had written it in whatever way it thinks is best (modulo the as-if rule).

So yes, code which is only executed at runtime can be optimised. It's not that the optimiser runs the expression, it's that it rewrites it.

3

u/manni66 1d ago edited 1d ago

They can’t be removed as long as they have observable behavior.

Edit:

https://godbolt.org/z/h3M4s6rM4

uncomment the return to see the difference

3

u/alfps 23h ago

Any expression might be optimized if the compiler sees a way to do whatever it is, more efficiently, or with less memory consumption.

Consider this program:

#include <print>
using   std::print;

auto main() -> int
{
    const int n = 12;
    int sum = 0;
    for( int x = 1; x <= n; ++x ) { sum += x; }
    print( "The sum of 1 through {} is {}.\n", n, sum );
}

As you can see on Godbolt the g++ compiler manages to optimize that loop down to the number it produces, 78. Unfortunately Visual C++ does not, it apparently performs the looping (or an unrolled version) at run time.

To avoid the looping and still support possible changes to n you can write an expression like n*(n + 1)/2. That's a manual optimization. I doubt that a current compiler is able to do that, but you can check; it would not surprise me to be surprised, to put it that way.

2

u/MikailBag 1d ago

Perhaps I don't understand what you wanted to ask, but any expression can be optimized to different agree or not optimized at all. This highly depends on compiler, its flags and actual code

1

u/Independent_Art_6676 19h ago edited 19h ago

maybe think of it like this. If you have const a = 2 and const b = 5 then the compiler can understand that a*b is 10 and put 10 in where you type a*b. But if you read a from a keyboard or file or network etc, then it has no idea what a*b is, and must multiply the current value by b even if b is a constant, as the value is just not known and must be computed. Compilers can deduce a lot, but sometimes if its deep enough or confusing enough it can fail to optimize, less and less as they get better and better at it and also less with the 'new' (not really now?) const tools we have to point it in the right direction.

Things that are computed from external (like user typed in as above etc) are "run time" and cannot be optimized (pre-computed). They can be optimized in other ways (like rewriting the math/logic).