0

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.

1

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

2

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().

1 Comment

Oh yeah, that was a mistake on my part.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.