5

This is a simplified version what I would like to do.

constexpr float f(float a, float b){
    constexpr float temp = a+b;
    return temp*temp*temp;
}

In my version, a+b is something much more complicated, so I don't want to cut and paste it three times. Using 3*(a+b) is also not a working solution for the real function. I'm trying to keep the question related to syntax, and not algebra. I can get it to work by moving a+b to it's own constexpr function, but I'd prefer to not pollute the namespace with otherwise useless functions.

1
  • 4
    This is the #1 suckiest thing about constexpr. Commented Oct 14, 2012 at 18:12

2 Answers 2

6

As you've discovered, you can't declare variables, even constexpr ones, inside the body of a constexpr function.

It's still possible to factor out a common expression, by passing it in as an argument to a second constexpr function. For the example you've given here:

constexpr float pow3(float c) {
    return c*c*c;
}

constexpr float f(float a, float b) {
    return pow3(a+b);
}
Sign up to request clarification or add additional context in comments.

Comments

3

This is not permitted in C++11, but is now permitted in C++14.

See https://en.wikipedia.org/wiki/C%2B%2B14#Relaxed_constexpr_restrictions

3 Comments

You should do it the other way around. f2(float temp) { return temp * temp * temp; } and f(float a, float b) { return f2(a + b); }. That way you avoid the 3 calls.
This doesn't matter with constexpr because it indicates to the compiler that the results of the function can be memorized and/or evaluated at compile time. The compiler will call temp once and reuse the value 3 times. Grand total of 1 add, 3 multiplies your way and my way. But, as I said in the intro, I simplified the problem because the question isn't about algebra.
@JohnK: It doesn't matter for the compiled code, but it does matter for the humans writing and reading that code. For the one writing it: Less repetition = less opportunity to make an error. For the one reading it: It is easier to figure out that you've got three times the same value.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.