๐ŸŽ“ A1Learner
๐Ÿ”
0 of 40 lessons completed

C++ Parameters

A parameter is a named input that a function receives from a call. An argument is the value a call passes for a parameter.

One parameter

The greet function takes a string parameter named name. The call passes the text Hana.

#include <iostream>
#include <string>

void greet(std::string name) {
  std::cout << "Hello, " << name << std::endl;
}

int main() {
  greet("Hana");
  return 0;
}

Two parameters

The printSum function takes two int parameters. It prints their sum.

#include <iostream>

void printSum(int a, int b) {
  std::cout << a + b << std::endl;
}

int main() {
  printSum(4, 5);
  return 0;
}

A value comes back

The doubleNumber function sends back twice its input. Main saves that value in a variable and prints it.

#include <iostream>

int doubleNumber(int n) {
  return n * 2;
}

int main() {
  int result = doubleNumber(6);
  std::cout << result << std::endl;
  return 0;
}

A default parameter value

The first call leaves the argument out, so the default value 10 fills the parameter. The second call passes 25 instead.

#include <iostream>

void printPrice(int price = 10) {
  std::cout << price << std::endl;
}

int main() {
  printPrice();
  printPrice(25);
  return 0;
}

Passing by reference swaps values

The swapValues function takes two reference parameters. Changing them changes the variables in main.

#include <iostream>

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

int main() {
  int x = 3;
  int y = 8;
  std::cout << x << " " << y << std::endl;
  swapValues(x, y);
  std::cout << x << " " << y << std::endl;
  return 0;
}

Example

#include <iostream>

int area(int width, int height) {
  return width * height;
}

int main() {
  std::cout << area(3, 4) << std::endl;
  std::cout << area(5, 2) << std::endl;
  return 0;
}

Key points

  • A parameter sits inside the parentheses in a function definition.
  • An argument is the value a call passes for a parameter.
  • A function can take more than one parameter, split by commas.
  • A function with a type before its name returns a value to the caller.
  • A default value fills a parameter when a call leaves the argument out.
  • An & after a type makes the parameter another name for the argument variable.

In this example, area takes a width and a height and sends back their product. The first call works out 3 times 4 as 12. The second call works out 5 times 2 as 10.

Note

Changing a reference parameter changes the variable in the caller.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

A call leaves out an argument for a parameter that has a default value. What does the function use?