I
last month
Iancountry asked

Can we assign a default value to a function parameter in C++, like void find_square(int number = 12)?

Abhay Jajodia
Expert
last month
Abhay Jajodia answered

Hello An, really nice question.

Yes, in C++ you can assign a default value to a function parameter, just like this:

void find_square(int number = 12) {
    int result = number * number;
    cout << "Square of " << number << " is " << result << endl;
}

Here’s what that means:

  • If you call the function without an argument:

    find_square();    // uses number = 12
    
  • If you call it with an argument:

    find_square(5);   // uses number = 5
    

So C++ will use the value you pass in if you provide one, and if you don’t, it falls back to the default value you wrote in the function definition.

Just remember:

  • This works in C++, not in plain C.

  • Default values are usually written in the function declaration (or definition), not repeated in multiple places.

If you have further questions, I'm here to help.

C++
This question was asked as part of the Learn C++ Basics course.