Jump to content
  • Advertisement
MarcusAseth

Constexpr doubt :/

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?! :S

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 this post


Link to post
Share on other sites
Advertisement

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 this post


Link to post
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 this post


Link to post
Share on other sites

I will :D

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

 

Edited by MarcusAseth

Share this post


Link to post
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 this post


Link to post
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 this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

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!