Lesson 93 +10 XP

Parameters and Arguments

Parameters and Arguments

A function becomes far more useful when it can work with different inputs. That's what parameters are for.

Parameters

Parameters are variables declared inside the parentheses of the function definition. They act like inputs the function can use:

void myFunction(string fname) {
  cout << fname << " Doe";
}
  • string fname declares a parameter that will hold whatever text is passed in.
  • Inside the body, fname behaves like a normal variable.
  • The function can use fname however it likes.

Arguments

When you call the function, you supply the actual value - that's the argument:

myFunction("Liam");   // prints "Liam Doe"
myFunction("Jenny");  // prints "Jenny Doe"
myFunction("Anja");   // prints "Anja Doe"

Same function, different names. The argument fills in the parameter for that call.

Pass-by-value

By default C++ passes arguments by value: the function receives a copy. Whatever you do to a parameter inside the body, the caller's variable stays unchanged:

void tryChange(int y) {
  y = 99;                       // changes the copy
}
int main() {
  int x = 5;
  tryChange(x);
  cout << x;                    // still prints 5
  return 0;
}

TL;DR

  • Parameters are the variables declared in the function's parentheses: void f(string name).
  • Arguments are the values you pass at the call: f("Liam").
  • The argument is copied into the parameter.
  • Pass-by-value gives the function a copy, so the caller's value cannot change.