1

i have a little question, how can i initialize default arguments in an function?

    #include <iostream>
    #include <cmath>

    using namespace std;
    float area(float a, float b, float c);
    float area(float a, float b=a, float c =a);


    int main() {

        cout << area(10) << endl;
        return 0;
    }

float area(float a, float b, float c){
    return a*b*c
    }

i am getting errors, how can i impelent correctly?

2
  • Please post the errors you are getting. And also, read this post for how to ask better questions, which will help people give you better answers. Finally, this tutorial is a great place to start learning C++. Commented Apr 30, 2016 at 21:54
  • Note that only error here is that your are using local variable a as default parameter. Since multiple declarations are allowed, if you replace a by something that can be evaluated when function is called everything will work fine, but you will have only 1 function. Commented Apr 30, 2016 at 21:58

3 Answers 3

3

You are going to have to use overloading instead of default parameters:

#include <iostream>
#include <cmath>

using namespace std;
float area(float a, float b, float c);
float area(float a);

int main() {

    cout << area(10) << endl;
    return 0;
}

float area(float a, float b, float c){
  return a*b*c;
}
float area(float a){
  return area(a,a,a);
}
Sign up to request clarification or add additional context in comments.

Comments

1

If you want default value for b and c to be the value of a then you should use overloading:

float area(float a, float b, float c){
   return a*b*c
}
float area(float a) {
   return area(a, a, a);
}

C++ does not allow to use parameters as default arguments. So this

float area(float a, float b=a, float c =a);
                           ^^          ^^

is an Error.

Comments

0

In C++

you should prototype and implement the code for only one method including the optional parameters and the default values is the optional parameter is ommitted must be a constant and not an unknown value...

    float area(float a, float b=0, float c=0);
    int main() {
        cout << area(10) << endl;
        return 0;
    }

float area(float a, float b=-1, float c =-1);){
    if(b==-1 ||c==-1)
    {
        return a*a*a;
    }else
    {
        return a*b*c;
    }
}

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.