Constexpr doubt :/

Started by
7 comments, last by MarcusAseth 6 years, 7 months ago

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;
}

 

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++. ;)

xD

 This language is so subtle... x_x  Thanks Kylotan :)

 

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 ;) .

🧙

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

 

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 ;)

🧙

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

Omae Wa Mou Shindeiru

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

This topic is closed to new replies.

Advertisement