Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385098

Run-time operators in C++

What is the definition of compile-time and run-time operator in C++?

I know that sizeof() is a compile-time operator in C++ but which are the run-time operators?


(Originally posted for by bc90; I did not wish to waste the answer that I posted before it became clear he only wanted a C answer. Hey, perhaps this can help "clarify" someone's "doubts" one day.)

Upvotes: 10

Views: 944

Answers (1)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385098

It's not as simple as that. There is no "list of runtime operators" or "list of compile-time operators". There are operators, and many of them may be optimised to be "executed" by the compiler rather than coded into the program as an operation to be performed at runtime.

The obvious one is sizeof, which never needs to be deferred until program execution. In fact, speaking generally, operators which act on types may be expected to be purely a semantic operation with no reliance on run-time information. As another example, there is absolutely no reason for const_cast to have any run-time relevance, seeing as const doesn't even exist in your compiled program. A static_cast may be optimised away, but that would depend on what the relevant conversion operators do.

What may not be so obvious is that many expressions that invoke, say, arithmetic operators, may be optimised away.

For example:

const int x = 2 + 4;

That addition is not going to be performed at runtime unless your compiler is very, very silly. But does that make operator+ a "compile-time operator"? No.

And the function call operator () is only ever going to be invokable at compile-time if the applicable constexpr rules apply, or the function definition is visible in the same translation unit as the call site and is sufficiently trivial.

Whilst we're at it, reinterpret_cast disqualifies an expression from being constexpr. This is reasonably unintuitive but, according to the rationale in CWG issue #1384:

Although reinterpret_cast was permitted in address constant expressions in C++03, this restriction has been implemented in some compilers and has not proved to break significant amounts of code. CWG deemed that the complications of dealing with pointers whose tpes [sic] changed (pointer arithmetic and dereference could not be permitted on such pointers) outweighed the possible utility of relaxing the current restriction.

My point is that, really, it's not worth trying to come up with general rules for this: the process of C++ program compilation is just not that straightforward. You have to examine what your program is doing on a case-by-case basis.

However, I do appreciate that you are trying to answer a poor exam question. For that, you have my sympathies.

Upvotes: 13

Related Questions