Parameters
Overview
A function that always does the exact same thing (like printing 'Hello') isn't very useful. Functions need to be dynamic, adapting their logic based on external input.
Parameters act as the 'Inputs' to a function. They are essentially local variables that the function expects you to fill with data when you call it. The data you actually pass into the function during the call is known as the 'Argument'. This allows you to write a single calculateArea(int width, int height) function and use it for thousands of different rectangles.
Syntax
// 'a' and 'b' are PARAMETERS
void printSum(int a, int b) {
std::cout << "Sum is: " << (a + b) << "\n";
}
int main() {
int x = 10, y = 20;
// 'x' and 'y' (or literal numbers like 5, 10) are ARGUMENTS
printSum(x, y);
printSum(5, 15);
return 0;
}Common Pitfalls
- Type Mismatches. C++ is strictly typed. If a function parameter demands an
int, and you pass it astd::string, the program will refuse to compile. If you pass adoubleinto anintparameter, C++ will implicitly truncate it (chop off the decimal), silently altering your data. - Argument Count Mismatch. If a function is defined with 3 parameters, you MUST pass exactly 3 arguments. Passing 2 or 4 will instantly halt compilation.
Interview Questions
A Parameter is the variable defined in the function's signature (e.g., void func(int x) -> x is the parameter). An Argument is the actual physical data or value passed into the function when it is executed (e.g., func(5) -> 5 is the argument).
Real-World Example
Passing multiple parameters of different data types to dynamically render UI elements.
#include <iostream>
#include <string>
// Function accepts text, dimensions, and a boolean flag
void renderButton(std::string text, int width, bool isEnabled) {
if (!isEnabled) {
std::cout << "[DISABLED] ";
}
std::cout << "Rendering '" << text << "' at width " << width << "\n";
}
int main() {
renderButton("Submit", 200, true);
renderButton("Delete", 150, false);
return 0;
}Check Your Knowledge
Test your understanding of Parameters with these quick questions.