Search code examples
c++constexprlocal-functions

C++ constexpr function-definition is not allowed


I'm trying to learn C++, specifically C++11 since we mostly study C, and I've ran into an error while trying to test what "constexpr" can do.

Test 1:

#include <iostream>;

using namespace std;

int main()
{
    int x = 3;
    int y = 4;
    constexpr int Sum(int a, int b) {return a + b;}
    cout << Sum(x,y);
    return 0;
}

Test 2:

#include <iostream>;

using namespace std;

int main()
{
    int x = 3;
    int y = 4;
    constexpr int Sum() {return 3+4;}
    cout << Sum();
    return 0;
}

On both cases, it gave me the following errors:

E:\C++\Lesson1\main.cpp|9|error: a function-definition is not allowed here before '{' token| E:\C++\Lesson1\main.cpp|10|error: 'Sum' was not declared in this scope|

Am I doing something wrong or I have to do something to the compiler? (Using Code Blocks and I have C++11 enabled.


Solution

  • Try moving your constexpr function definition outside of main().