Example of Default Argument in C++

WAP to calculate the price of n items. Pass a number of items and unit price to the function and return the total price. If the unit price is not specified using the default price.

Default Argument in C++ is a value provided to a function declaration that is automatically assigned by a compiler if the caller of the function doesn’t provide a value for argument with a default value.

Example: int sum(int, int = 0)

Also, check out: Calculate area in C++ | Function overload

Program

// WAP to calculate the price of n items. Pass a number of items and unit price to the function and return the total price. If the unit price is not specified using the default price.

#include<iostream>

using namespace std;

int totalPrice(int, int=25000);

int main() {
    int n, price, total;

    cout<<"Enter number of items"<<endl;
    cin>>n;
    
    cout<<"Enter the price of item, 0 for default value."<<endl;
    cin>>price;

    total = !price ? totalPrice(n) 
            : totalPrice(n, price);

    cout<<"Total price is "<<total;

    return 0;
}

int totalPrice(int n, int p) {
    return n*p;
}

Output

Without default value

Enter the number of items
3
Enter the price of item, 0 for default value.
500
Total price is 1500

With default value

Enter number of items
3
Enter the price of item, 0 for default value.
0
Total price is 75000

0 0 votes
Article Rating
Subscribe
Notify of
0 Comments
Inline Feedbacks
View all comments