Reputation: 3122
I've been using C++ for a bit but never really got into great detail. Recently found out about constexpr
and I think it's got great potential for micro-optimizations, though I struggle to see how to properly use it. Considering the following:
#define squared(n) (n * n)
and
constexpr int squared(int n) {
return n * n;
}
They both output the same thing, but I'm sure they are very different. From my knowledge define directives get replaced at compile-time so any instance of squared(n)
simply becomes (n * n)
.
Obviously this is a simple example, but I'd like to know where does constexpr
come into play? Is it meant to used for operations more complex than simple text substitution? What is the main advantage of using it and how is it different from normal expressions?
Upvotes: 3
Views: 707
Reputation: 171167
They don't output the same thing at all. Consider this call:
squared(x++);
Or this class:
struct Number
{
float value() const;
float squared() const;
// ... other members
};
Both of these will fail miserably if squared
is a function-like macro.
So, as always: don't use macros where another feature of the language can work as well. You could say that constexpr
simply allows us to use macros in fewer places - a good thing.
And there's one more, very important distinction: constexpr
functions can be (and indeed often are) recursive. Function-like macros cannot.
Upvotes: 5