0

I am getting an error when trying to run this code

In function 'int main()':
error: 'area' was not declared in this scope

I cannot find a clear solution to the problem.

#include <iostream>

using namespace std;

int main() {

    area(13.3, 67.4);

    return 0;
}

void area(int a, int b){
    cout << "The area is " << a * b << endl;
}

void area(float a, float b){
    cout << "The area is " << a * b << endl;
}

void area(double a, double b){
    cout << "The area is " << a * b << endl;
}
2
  • you need to have the function declarations at least before you call it Commented Sep 27, 2018 at 2:29
  • @rial Next time please copy the error messages and post them as text instead of a picture. Commented Sep 27, 2018 at 2:33

2 Answers 2

2

You need to declare the functions before you can use them.

Either forward declare them:

#include <iostream>

using namespace std;

// forward declarations
void area(int a, int b);
void area(float a, float b);
void area(double a, double b);

int main() {
    area(13.3, 67.4);
    return 0;
}

void area(int a, int b){
    cout << "The area is " << a * b << endl;
}

void area(float a, float b){
    cout << "The area is " << a * b << endl;
}

void area(double a, double b){
    cout << "The area is " << a * b << endl;
}

Otherwise, move the implementations above main():

#include <iostream>

using namespace std;

void area(int a, int b){
    cout << "The area is " << a * b << endl;
}

void area(float a, float b){
    cout << "The area is " << a * b << endl;
}

void area(double a, double b){
    cout << "The area is " << a * b << endl;
}

int main() {
    area(13.3, 67.4);
    return 0;
}

That being said, since the implementations are exactly the same, just with different data types, consider using a single templated function instead:

#include <iostream>

using namespace std;

template<typename T>
void area(T a, T b){
    cout << "The area is " << a * b << endl;
}

int main() {
    area<double>(13.3, 67.4);
    return 0;
}
Sign up to request clarification or add additional context in comments.

Comments

0

Put functions prototypes above your main function and you should be fine.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.