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.
#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;
}
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;
}
Boost your C++ proficiency by studying these closely connected core modules:
Compile-time functions and eliminating call overhead.
Defining multiple functions with identical names.
Deep dive into reference parameters and aliasing.