C++ PROGRAMMING · 8 MIN STUDY

Functions, parameters, and return values

A function names one task so the program can call it with data and receive a result.

Learning objectives

  • Define and call a value-returning function.
  • Distinguish parameters from arguments.
  • Describe a function’s input/output contract.

Prerequisites: variables, basic expressions, and main. You should be able to identify a value and a statement before studying function calls.

One task, one name

Complete C++17 program
#include <iostream>

int add(int left, int right) {
    return left + right;
}

int main() {
    int total = add(4, 6);
    std::cout << total << '\n';
}
Expected output 10

left and right are parameters in the function definition. The values 4 and 6 are arguments at this call. The expression left + right is evaluated, then return sends the result to the caller.

Trace

The call creates parameter values 4 and 6. The function computes 10 and finishes. The initialization stores 10 in total. The function’s return type, int, tells callers what kind of result to expect.

Common mistakes and applications

  • Do not declare an int function without returning an int on every reachable path.
  • Choose names that reveal the contract; add is clearer than doThing.
  • Functions isolate conversion, validation, calculations, and formatting so each can be tested separately.

Practice

  1. In int area(int width, int height), identify the parameters.
  2. What does return width * height; send to the caller?
  3. Why is a function with a non-void return type expected to return a value on every reachable path?
Show reasoned answers
  1. width and height.
  2. The product of the two parameter values.
  3. The caller expects a result of the declared return type; reaching the end without returning a value from an ordinary value-returning function leads to undefined behavior.

References