Home > Software design >  not passing sufficient arguments in the functions still the code is running
not passing sufficient arguments in the functions still the code is running

Time:09-17

#include <iostream>

using namespace std;

void print(string str,int a=0)
{ 
  cout<<str;
}

int main()
{
    string str="hello world";
    print(str);
    return 0;
}

why is the code working if I'am only passing one argument whereas the function needs two arguments

CodePudding user response:

Whenever you have a function with a defaulted argument

void some_func(int a, int def = 0)
{
    //something
}

The following call

some_func(42);

is converted into

some_func(42, 0);

And you can also call the function with two arguments, such as some_func(42, 1);

CodePudding user response:

It works because you defined this int on a function declaration. The compiler knows that a =0 and is an int type. However if you lets say call this function like this:

print(str,10); 

int a will have value of 10 instead of 0.

CodePudding user response:

You are declaring function with one argument to have a default initial value, that is why you are able to call function without that argument.

if not passing that argument to function, its initial value that you declared, is used.

  • Related