Default Arguments Example

Hi cplusplus.com forum,
could someone help me work out how to compile this example?


#include <iostream>
using namespace std;

void showVolume(int length, int width = 1, int height = 1);
// Returns the volume of a box.
// If no height is given, the height is assumed to be 1.
// If neither height nor width is given, both are assumed to be 1.
int main()
{
showVolume(4, 6, 2);
showVolume(4, 6);
showVolume(4);
return 0;
}
void showVolume(int length, int width, int height)

It should compile fine if you finish off writing the function at the bottom. If it's to return a value, though, you need to make it an integer returning function (assuming it's an integer because that's what your parameters are).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int showVolume(int length, int width int height)
{
   return length * width * height;
}

// In main...
// You can either store the returned value or print it directly

// Printing
cout << showVolume(4,6,2);

// Storing
int volume;
volume = showVolume(4);


Hope this helps.
#include <iostream>
using namespace std;

int showVolume(int length, int width = 1, int height = 1);
int main()
{
int vola,volb,volc;
vola=showVolume(4, 6, 2);
volb=showVolume(4, 6);
volc=showVolume(4);
return 0;
}
int showVolume(int length, int width=1, int height=1)
{
int volume;
volume=length*width*height;
return volume;
}


the variables vola,volb,volc will hold the values for the volume of different cuboids and the function showVolume will calculate and return the value of the volumes.



Happy Programming :-)
Last edited on
You can also use your function the following way

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>

using namespace std;
 
// Returns the volume of a box.
void showVolume( int length, int width, int height );

int main()
{
// Returns the volume of a box.
    showVolume(4, 6, 2);

// If no height is given, the height is assumed to be 1.
    void showVolume( int length, int width, int height = 1 );
    showVolume(4, 6);

// If neither height nor width is given, both are assumed to be 1.
    void showVolume( int length, int width = 1, int height = 1 );
    showVolume(4);

    return 0;
}

void showVolume(int length, int width, int height)
{
   std::cout << "Volume is equal to " << length * width * height << std::endl;
}
Last edited on
Topic archived. No new replies allowed.