Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C++11 is sqrt defined as constexpr?

In C++11 is std::sqrt defined as constexpr, i.e. can it legally be used from other constexpr functions or in compile-time contexts like array sizes or template arguments? g++ seems to allow it (using -std=c++0x), but I'm not sure I can take that as authoritative given that c++0x/c++11 support is still incomplete. The fact that I can't seem to find anything on the Internet makes me unsure.

It seems like this should be something one could easily find out using Google, but I've tried (for 40 minutes now...) and couldn't find anything. I could find several proposals for adding constexpr to various parts of the standard library (like for example this one), but nothing about sqrt or other math functions.

like image 377
sepp2k Avatar asked Dec 24 '11 02:12

sepp2k


People also ask

What is constexpr in C ++ 11?

The keyword constexpr was introduced in C++11 and improved in C++14. It means constant expression. Like const , it can be applied to variables: A compiler error is raised when any code attempts to modify the value. Unlike const , constexpr can also be applied to functions and class constructors.

How do I know if a function is constexpr?

The easiest way to check whether a function (e.g., foo ) is constexpr is to assign its return value to a constexpr as below: constexpr auto i = foo(); if the returned value is not constexpr compilation will fail.

Does C have constexpr?

No, no such thing exists in C.


2 Answers

std::sqrt is not defined as constexpr, according to section 26.8 of N3291: the C++11 FDIS (and I doubt they added it to the final standard after that). One could possibly write such a version, but the standard library version is not constexpr.

like image 89
Nicol Bolas Avatar answered Sep 28 '22 04:09

Nicol Bolas


Just in case anyone is interested in a meta integer square root function, here is one I wrote while a ago:

constexpr std::size_t isqrt_impl     (std::size_t sq, std::size_t dlt, std::size_t value){     return sq <= value ?         isqrt_impl(sq+dlt, dlt+2, value) : (dlt >> 1) - 1; }  constexpr std::size_t isqrt(std::size_t value){     return isqrt_impl(1, 3, value); } 
like image 38
Khaled Alshaya Avatar answered Sep 28 '22 03:09

Khaled Alshaya