C++ Function Parameters

Function parameters in C++ are values passed to a function when it is called. They allow the function to receive input data and perform operations using that data. Parameters are specified in the function declaration and definition.

Syntax

return_type function_name(type1 param1, type2 param2, ...) {
    // code using param1, param2, ...
}

Where:

  • type1, type2, … – Data types of the parameters.
  • param1, param2, … – Names of the parameters used inside the function.

Example Program with Parameters

#include <iostream>
using namespace std;

// Function with parameters
void greet(string name, int age) {
    cout << "Hello, " << name << "! You are " << age << " years old." << endl;
}

int main() {

    greet("Alice", 25); // Function call with arguments
    greet("Bob", 30);

    return 0;
}

Output

Hello, Alice! You are 25 years old.
Hello, Bob! You are 30 years old.

Types of Function Parameters

  • Pass by Value – The function gets a copy of the argument. Changes inside the function do not affect the original variable.
  • Pass by Reference – The function gets the address of the argument. Changes inside the function affect the original variable.
  • Default Parameters – You can provide default values that are used if the argument is not passed.

Example: Default Parameter

#include <iostream>
using namespace std;

// Function with default parameter
void greet(string name, int age = 18) {
    cout << "Hello, " << name << "! Age: " << age << endl;
}

int main() {

    greet("Alice", 25); // Age provided
    greet("Bob");       // Uses default age 18

    return 0;
}

Output

Hello, Alice! Age: 25
Hello, Bob! Age: 18

Important Notes

  • Parameters allow you to pass data to functions and make them reusable for different inputs.
  • Default parameters must appear at the end of the parameter list.
  • Pass by reference is used when you want the function to modify the original variable.

Next Topic

Next, learn about Return Values in C++ Functions.