-3

I have a snippet of code where C++ functions are declared with default argument of char and int type.

#include <iostream>

using namespace std;

int print(char c = '*', int num = 10);


int print(char c, int num)

{

    for (int i = 0; i < num; i++)

    {

        cout << c << endl ;

    }

    cout << endl;

    return 0;

}

int main()

{

    int rep;

    char letter;

    cout << "Enter a character : ";

    cin >> letter;

    cout << "Enter the number of times it has to repeat : ";

    cin >> rep;

    

    print(letter, rep);



    print(rep);

    print(letter);

    

    return 0;

}

There is no output for print(rep);

even though default argument for character is given. Any idea why this is happening?

I tried to use default arguments, but default argument of char is not working as intended and there is no intended character output for that.

mr_coder
  • 3
  • 2
  • `print(rep)` is equivalent to `print(static_cast(rep), 10)`. How default arguments work should have been mentioned when they were introduced in your favourite C++ book. – molbdnilo Mar 03 '23 at 14:02

1 Answers1

2

Arguments are still in order. You can only omit arguments from the end. When you call print(rep), the integer gets converted to a char and num gets defaulted. You'll notice if you enter, say, "65" (the code for 'A') as the value for rep.

Sebastian Redl
  • 69,373
  • 8
  • 123
  • 157