Public Group

Constexpr doubt :/

This topic is 423 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

I may have got this wrong, but I thought that stuff marked with the keyword constexpr had to be known at compile time.

Then why in my example below, where I pass to the constexpr function a value that is only know at run time, I don't get any errors?!

size_t fib(size_t n)
{
if (n <= 1)
{
return 1;
}
return fib(n - 1) + fib(n - 2);
}

constexpr size_t fib_constexpr(size_t n)
{
if (n <= 1)
{
return 1;
}
return fib(n - 1) + fib(n - 2);
}

int main()
{
int n;
cin >> n;
cout << fib(n) << endl;
cout << fib_constexpr(n) << endl;
return 0;
}

Edited by MarcusAseth

Share on other sites

Objects/values that you declare with constexpr have to be evaluated at compile time.

Functions that you declare with constexpr can be evaluated at compile time, if all their arguments are also constexpr (or other compile time constants).

It's confusing - welcome to modern C++.

Share on other sites

This language is so subtle... x_x  Thanks Kylotan

Share on other sites

Really recommend reading: Scott Meyers' "Effective Modern C++: 42 Specific Ways to Improve Your Use of C++11 and C++14", best and most interesting C++11/14 "2nd book" (i.e. the author has not the intention of teaching the basics, but rather focuses on best practices while diving straight into the content) available.

More particularly, it tackles a.o. constexpr and () vs {} initializers  .

Share on other sites

I will

I am still at Programming Principles and practice using C++ 2nd edition, around page 650 or something. Got to finish this first

Edited by MarcusAseth

Share on other sites
23 minutes ago, MarcusAseth said:

around page 650 or something

Effective Modern C++ has only 300 pages so that should be a walk in the park

Share on other sites

Declaring a function constexpr means that it is "certified" for compile-time use, to compute constants, in addition to being compiled and callable like a non-constexpr function.

In your program there is no call with constant arguments (which would be optimized away) and the two functions are basically identical. See them on Godbolt: https://godbolt.org/g/JJ4LsQ

Share on other sites

That is impossible for me to decipher, though one day learning assembly could do for an interesting hobby I think, got to keep that in mind

1. 1
2. 2
Rutin
19
3. 3
4. 4
5. 5

• 9
• 9
• 9
• 14
• 12
• Forum Statistics

• Total Topics
633282
• Total Posts
3011206
• Who's Online (See full list)

There are no registered users currently online

×

Important Information

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!