Advantage of having compiler do calculations

If the compiler isn't doing calculations, what is? And what is the advantage of having the compiler do calculations?
compilers turn source code that humans can read into machine language that the computer can execute.

Your question is not making much sense.

So I am hearing that using constexpr lets you do compile time calculations. I don't understand what the advantage of that is and what the alternative is.
oh, ok.

computing
a-b
tells the computer to go to a memory location a, go to a memory location b, subtract the two, and store the result somewhere or move it off to use it.

If a is always 3 and b is always 1, that is a lot of work.
its better if you just stored 2 somewhere, right?
then the machine can go to memory location, fetch 2, and use it, a lot less trouble.

The compiler can resolve many constants this way, avoiding having to recompute the results, which is much more efficient. The little things add up in long running programs, and that efficiency translates to run-time.

if you had told the compiler the values were variables (could change somehow) it has to do the harder effort each time. That is necessary when you do, indeed, have changing values. But constants can be used very efficiently .. a common example is pi/180 and 180/pi are often saved as constants to convert to and from radians.

Last edited on
so why would you need a constexpr function to do this?
you don't always. You use those to TELL the compiler what you want it to do, in cases where it might not be able to do it without being told to do so, kind of like inline functions or other compiler hints and suggestions. Sometimes, the human can tell the compiler things that makes the code better.

Here...
http://en.cppreference.com/w/cpp/language/constexpr



You are 100% correct, the compiler can constant out the simple examples I gave without help. I was trying to explain it in too simple of terms, perhaps. The actual use of the things is fairly involved, as you can see in that link.

Last edited on
Okay cool, thanks for the help!
Topic archived. No new replies allowed.