Saturday, April 19, 2025

C++ Default Arguments

Default arguments are used when while calling functions we forget to enter arguments or there's no need for them.

It's easy, while creating parameters just state name, data type and initial (default) value, just as in this example where we have 2 default parameters, y with value 5000 and z with value 1000.

But we always must pass value for x, otherwise compiler will complain: 

#include <iostream>
#include <cstdlib>

using namespace std;

void defaultArgs(int x, int y = 5000, int z = 1000);

int main() {

    defaultArgs(4);

    return 0;

}

void defaultArgs(int x, int y, int z) {
    cout << "X: " << x << endl;
    cout << "Y: " << y << endl;
    cout << "Z: " << z << endl;
}

Result:

X: 4
Y: 5000
Z: 1000

Process returned 0 (0x0)   execution time : 0.059 s
Press any key to continue.

When we don't provide values while calling function, default arguments will step in.

Otherwise, if all of them have default value, forgetting one/more of them will not be a problem for a compiler:

#include <iostream>
#include <cstdlib>

using namespace std;

void defaultArgs(int x = 3000, int y = 5000, int z = 1000);

int main() {

    defaultArgs();
    defaultArgs(2);
    defaultArgs(3, 4);
    defaultArgs(1, 2, 3);

    return 0;

}

void defaultArgs(int x, int y, int z) {
    cout << "X: " << x << endl;
    cout << "Y: " << y << endl;
    cout << "Z: " << z << endl;
    cout << "---------------------------" << endl;
}

Result:

X: 3000
Y: 5000
Z: 1000
---------------------------
X: 2
Y: 5000
Z: 1000
---------------------------
X: 3
Y: 4
Z: 1000
---------------------------
X: 1
Y: 2
Z: 3
---------------------------

Process returned 0 (0x0)   execution time : 0.057 s
Press any key to continue.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...