Use constexpr case and define
I used C ++ a little, but didn't understand very much. Found out about recently constexpr
and I think it got a lot of potential for micro-optimization, although I'm struggling to figure out how to use it correctly. 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. As far as I know, directive definitions are replaced at compile time, so any instance squared(n)
just becomes (n * n)
.
Obviously this is a simple example, but I would like to know where does it work constexpr
? Is it intended for more complex operations than simple text replacement? What is the main advantage of using it and how does it differ from normal expressions?
source to share
They don't output the same thing. Consider this call:
squared(x++);
Or this class:
struct Number
{
float value() const;
float squared() const;
// ... other members
};
Both of them will fail if squared
is a functionally similar macro.
So, as always: do not use macros where another language function might work. We could say that it constexpr
just allows us to use macros in fewer places is a good thing.
And there is one more, very important difference: functions constexpr
can be (and indeed often) recursive. Functional macros cannot.
source to share