Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does MSVC++11 rejects constexpr qualification of a function?

So, playing around with constexpr, MSVC (Visual Studio 2012) gave me an error while trying to qualify my function with the constexpr keyword using this simple program (includes omitted):

constexpr int factorial(int n) {     return n <= 1 ? 1 : (n * factorial(n-1)); }  int main(void) {     const int fact_three = factorial(3);     std::cout << fact_three << std::endl;     return 0; } 

constexpr was underlined red with the following message:

Error : this declaration has no storage class or type specifier

and trying to compile the program gave the following output:

1>main.cpp(5): error C2144: syntax error : 'int' should be preceded by ';'

1>main.cpp(5): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int

It really puzzles me as it is the very example that Cppreference uses to illustrate the use of constexpr. At first I used a simple function that returned a literal, i.e. constexpr int func(){return 5;}, but which yielded the same error. I interpreted the first message as "it should be a member function of a struct or class", but the example from Cppreference shows that it's not necessary apparently.

So, what am I obviously missing here ?

like image 413
JBL Avatar asked Aug 29 '13 14:08

JBL


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.

Can a function return constexpr?

A constexpr function is a function that can be invoked within a constant expression. A constexpr function must satisfy the following conditions: It is not virtual. Its return type is a literal type.

Does constexpr improve performance?

In Conclusion. constexpr is an effective tool for ensuring compile-time evaluation of function calls, objects and variables. Compile-time evaluation of expressions often leads to more efficient code and enables the compiler to store the result in the system's ROM.

Are constexpr functions evaluated at compile-time?

A constexpr function that is eligible to be evaluated at compile-time will only be evaluated at compile-time if the return value is used where a constant expression is required. Otherwise, compile-time evaluation is not guaranteed.


1 Answers

Quite simply - because Visual Studio doesn't support constexpr (prior to Visual Studio 2015).

Note that MSVC++11 is Visual Studio 2012; VC++10 is Visual Studio 2010.

like image 158
Chowlett Avatar answered Sep 30 '22 07:09

Chowlett