C++ Functions: Declarations, Parameter Passing Modes & Best Practices

A Function is a reusable block of code that performs a specific task. Functions improve code modularity, readability, and maintainability. In C++, choosing the correct parameter-passing mechanism is critical for performance and safety.

1. Pass by Value vs Pass by Reference

#include <iostream>

// Pass by Value: Operates on a COPY (Original unchanged)
void tryToModify(int x) {
    x = 999;
}

// Pass by Reference: Operates directly on the ORIGINAL variable
void actuallyModify(int& x) {
    x = 999;
}

// Pass by Const Reference: Fast (Zero copy), Read-Only (Guaranteed safe)
void printBigData(const std::string& text) {
    std::cout << "Text length: " << text.length() << "\n";
}

int main() {
    int score = 50;

    tryToModify(score);
    std::cout << "After tryToModify: " << score << "\n"; // Still 50

    actuallyModify(score);
    std::cout << "After actuallyModify: " << score << "\n"; // Now 999!

    return 0;
}

2. Default Arguments in C++

C++ allows functions to have default parameter values. Default parameters must be assigned from right to left in the parameter list:

#include <iostream>

// Default argument for 'taxRate' is 0.05 (5%)
double calculateTotal(double subtotal, double taxRate = 0.05) {
    return subtotal + (subtotal * taxRate);
}

int main() {
    std::cout << "Default tax: " << calculateTotal(100.0) << "\n";      // Uses 0.05 -> 105.0
    std::cout << "Custom tax:  " << calculateTotal(100.0, 0.18) << "\n"; // Uses 0.18 -> 118.0
    return 0;
}

Frequently Asked Questions (FAQ) - Student & Interview Review

Q1. What is the difference between Pass by Value and Pass by Reference in C++?

In Pass by Value (void func(int x)), a copy of the argument is created on the function's stack frame; modifications do not affect the original variable. In Pass by Reference (void func(int& x)), the function receives an alias to the caller's variable; modifications directly change the original.

Q2. Why is 'Pass by Const Reference' (const T&) the gold standard for objects in C++?

Passing large objects (e.g. std::string, std::vector, or classes) by value requires copying all bytes, which is slow. Passing by 'const T&' passes only a memory address (pointer size) without copying, while guaranteeing the function cannot accidentally modify the caller's data.

Explore Related C++ Tutorials & Next Steps

Boost your C++ proficiency by studying these closely connected core modules:

Inline & constexpr

Compile-time functions and eliminating call overhead.

Function Overloading

Defining multiple functions with identical names.

C++ References

Deep dive into reference parameters and aliasing.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!