Lord Zsolt
Lord Zsolt

Reputation: 6557

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.

Upvotes: 0

Views: 757

Answers (2)

built1n
built1n

Reputation: 1546

Your problem

You put a semicolon after a preprocessor directive (#include). You should never do that, unless #define-ing something. This is making the compiler go nuts. Also, in addition to that, you cannot define a function within a function. You must define it outside, in global or class scope.

Solution

Remove the semicolon behind #include <iostream>. Move the constexpr definition above main().

Upvotes: 2

Nicola Musatti
Nicola Musatti

Reputation: 18236

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

Upvotes: 3

Related Questions