C++ Function Parameters

Passing data to functions effectively

๐Ÿ“ฅ What are Function Parameters?

Parameters allow functions to receive input data. They make functions flexible and reusable by accepting different values each time the function is called.


// Function with parameters
#include <iostream>
using namespace std;

void greet(string name, int age) {
    cout << "Hello " << name << ", you are " << age << " years old!" << endl;
}

int main() {
    greet("John", 25);
    greet("Sarah", 30);
    return 0;
}
                                    

Output:

Hello John, you are 25 years old!
Hello Sarah, you are 30 years old!

Types of Parameters

๐Ÿ“‹

Value Parameters

Copy of the original value

void func(int x) {
    x = 10; // Original unchanged
}
๐Ÿ”—

Reference Parameters

Direct access to original variable

void func(int &x) {
    x = 10; // Original changed
}
๐Ÿ‘†

Pointer Parameters

Memory address of variable

void func(int *x) {
    *x = 10; // Original changed
}
โš™๏ธ

Default Parameters

Default parameters let you specify fallback values for function arguments when callers omit them. For example, void printInfo(string name, int age = 18, string city = "Unknown") allows flexible calls with partial data. Defaults enhance API usability, reduce overloaded functions, and provide sensible behavior for common cases. Theyโ€™re especially useful in constructors, configuration functions, and libraries where parameters often have typical values, improving both code brevity and developer experience.

void func(int x = 5) {
    cout << x;
}

๐Ÿ”น Pass by Value

Pass by value copies the argument into the function, leaving the original variable unchanged. When you pass a variable by value, the function works with a local copy, so modifications inside the function donโ€™t affect the original. This is safe and prevents accidental side effects but can be inefficient for large data structures. Use pass by value for primitive types or when you want to ensure the original data remains untouched, as in mathematical computations or immutable operations.

#include <iostream>
using namespace std;

void changeValue(int x) {
    x = 100;  // Only changes the copy
    cout << "Inside function: x = " << x << endl;
}

int main() {
    int number = 5;
    cout << "Before function: number = " << number << endl;
    
    changeValue(number);
    
    cout << "After function: number = " << number << endl;
    return 0;
}

Output:

Before function: number = 5
Inside function: x = 100
After function: number = 5

๐Ÿ”น Pass by Reference

Pass by reference allows functions to directly modify the original variable using the & symbol. This avoids copying, improves performance for large objects, and enables functions to alter arguments, as seen in swap operations. References maintain a direct link to the original data, making them ideal for mutating inputs, returning multiple values, or handling complex types efficiently. However, care is needed to avoid unintended changes, and const references can be used for read-only access to large data.

#include <iostream>
using namespace std;

void changeValue(int &x) {
    x = 100;  // Changes the original variable
    cout << "Inside function: x = " << x << endl;
}

void swapNumbers(int &a, int &b) {
    int temp = a;
    a = b;
    b = temp;
}

int main() {
    int number = 5;
    cout << "Before function: number = " << number << endl;
    
    changeValue(number);
    
    cout << "After function: number = " << number << endl;
    
    int x = 10, y = 20;
    cout << "Before swap: x = " << x << ", y = " << y << endl;
    swapNumbers(x, y);
    cout << "After swap: x = " << x << ", y = " << y << endl;
    
    return 0;
}

Output:

Before function: number = 5
Inside function: x = 100
After function: number = 100
Before swap: x = 10, y = 20
After swap: x = 20, y = 10

๐Ÿ”น Default Parameters

Default parameters let you specify fallback values for function arguments when callers omit them. For example, void printInfo(string name, int age = 18, string city = "Unknown") allows flexible calls with partial data. Defaults enhance API usability, reduce overloaded functions, and provide sensible behavior for common cases. Theyโ€™re especially useful in constructors, configuration functions, and libraries where parameters often have typical values, improving both code brevity and developer experience.

#include <iostream>
using namespace std;

// Function with default parameters
void printInfo(string name, int age = 18, string city = "Unknown") {
    cout << "Name: " << name << ", Age: " << age << ", City: " << city << endl;
}

int main() {
    printInfo("Alice");                    // Uses default age and city
    printInfo("Bob", 25);                  // Uses default city
    printInfo("Charlie", 30, "New York");  // All parameters provided
    
    return 0;
}

Output:

Name: Alice, Age: 18, City: Unknown
Name: Bob, Age: 25, City: Unknown
Name: Charlie, Age: 30, City: New York

๐Ÿ”น Multiple Parameters

Functions can accept multiple parameters of different types to perform complex operations. For instance, a recordStudent() function might take name (string), ID (int), GPA (double), and grade (char). This allows bundling related data into a single call, improving organization and reducing function proliferation. Proper use of multiple parameters enhances function clarity, supports structured data handling, and is common in data processing, reporting, and object initialization routines in C++ applications.

#include <iostream>
using namespace std;

double calculateGrade(int totalPoints, int maxPoints, bool extraCredit = false) {
    double percentage = (double)totalPoints / maxPoints * 100;
    
    if (extraCredit) {
        percentage += 5; // Add 5% for extra credit
    }
    
    return percentage;
}

void displayStudentInfo(string name, int id, double gpa, char grade) {
    cout << "Student: " << name << endl;
    cout << "ID: " << id << endl;
    cout << "GPA: " << gpa << endl;
    cout << "Grade: " << grade << endl;
}

int main() {
    double grade1 = calculateGrade(85, 100);
    double grade2 = calculateGrade(78, 100, true);
    
    cout << "Grade 1: " << grade1 << "%" << endl;
    cout << "Grade 2: " << grade2 << "%" << endl;
    
    displayStudentInfo("John Doe", 12345, 3.75, 'A');
    
    return 0;
}

Output:

Grade 1: 85%
Grade 2: 83%
Student: John Doe
ID: 12345
GPA: 3.75
Grade: A

๐Ÿง  Test Your Knowledge

Which symbol is used for pass by reference?