Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

implicit constexpr?

Can C++11 compilers (and do they) notice that a function is a constexpr and treat them as such even if they are not declared to be constexpr?

I was demonstrating the use of constexpr to someone using the example straight from the Wikipedia:

int get_five() {return 5;}

int some_value[get_five() + 7]; // Create an array of 12 integers. Ill-formed C++

To my surprise the compiler was OK with it. So, I further changed get_five( ) to take a few int parameters, multiply them and return the result while still not being explicitly declared to be constexpr. The compiler was OK with that as well. It seems that if the compiler can do this there isn't much point to having the restrictions that are required in order to explicitly declare something constexpr.

like image 670
Arbalest Avatar asked Apr 01 '13 19:04

Arbalest


3 Answers

On a properly-functioning C++11 compiler, your code would be rejected.

Based on its being accepted, you're almost certainly using gcc (or something that closely emulates its bugs). gcc [depending somewhat on flags] can accept array sizes that aren't constant by any measure (e.g., depend on run-time input from the user) because they support an analog of C99 variable-length arrays in C++.

like image 56
Jerry Coffin Avatar answered Oct 10 '22 07:10

Jerry Coffin


A compiler can detect whether or not a function could have been declared with constexpr even when they haven't, for optimization purposes (i.e. computing the result of a function at compile-time). Compilers did that prior to C++11.

But for use in places that requires constant expressions, such as template parameters of integral type, it is against the standard to allow calls to functions that are not declared with the constexpr keyword.

like image 35
Zyx 2000 Avatar answered Oct 10 '22 06:10

Zyx 2000


GCC, as of GCC 12, supports the -fimplicit-constexpr command-line toggle which enables exactly that, for methods marked as inline.

  • Changelog: https://gcc.gnu.org/gcc-12/changes.html
  • Patch with some rationale and discussion: https://gcc.gnu.org/git/?p=gcc.git;a=commitdiff;h=87c2080b
like image 2
Jean-Michaël Celerier Avatar answered Oct 10 '22 07:10

Jean-Michaël Celerier