CodeBlanks Logo Icon CodeBlanks

Parameters

Learn to pass parameters to a function.

Parameter and argument

A function can take values from outside. In the definition you write a parameter: name in void greet(std::string name) is a parameter. The value you pass at the call is an argument: "Alex" in greet("Alex") is an argument.

The parameter behaves like a local variable inside the function. At call time the argument's value is copied into the parameter; this is called call by value. So even if you change the parameter inside the function, the caller's original variable is unaffected.

Call by value

The default behavior in C++ is call by value. When you call void addTen(int x) with addTen(n), the value of n is copied into x. Even if you write x = x + 10;, n stays the same.

This limits side effects and makes code easier to follow. If you want the function to modify the caller, you need a reference parameter; we cover that in a later level. For now, knowing parameters are copies is enough.

Practice Write parameterized greet and call it

Define a void greet(std::string name) function whose body is std::cout << "hi " << name << std::endl;. In main, call greet("Alex").

Starter code

main.cpp
#include <iostream>
#include <string>

// Define greet here

int main() {
    // greet call (argument: Alex)
    return 0;
}

Sample solution

main.cpp
#include <iostream>
#include <string>

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

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

Expected output

hi Alex

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match parameter and argument

Term Meaning
void greet(std::string name) Definition
greet("Alex") Call
name Parameter
"Alex" Argument

2 After calling void inc(int x) { x++; }, what is n? (n = 5)

main.cpp
int n = 5;
inc(n);
  • Compile error
  • n becomes undefined
  • n becomes 6
  • n stays 5 Correct answer

Explanation: in call by value the copy of n changes, n itself stays 5.

3 Complete the parameterized function

Question
void greet(std::string ____) { std::cout << name; }
Answer
void greet(std::string name) { std::cout << name; }

Explanation: the name parameter is used in the body.

All lessons in Beginner