TeachMate
My ProgressJoin Session

Functions

0/11 completed · ~0h 43m

All Topics
C++LearnFunctionsSyllabus
1 / 11

Functions

beginner
6 min read

What you'll learn

  • Break a task into small named functions.
  • Pass data with parameters and return a result.
  • Choose value, reference, or const-reference passing.

Functions are reusable blocks of code that perform a specific task.

Problem

A grade program must read marks, total them, average them, decide pass or fail, and print a report. Written as one long main(), it is hard to read and none of the logic can be reused.

Goal: Split the grade program into named tasks instead of one long main().

int main() {
    // read marks ...
    // total ...
    // average ...
    // decide pass/fail ...
    // print report ...
    // 100+ lines that all run together
}

Break the work into named tasks instead:

Pseudocode
main()
  readMarks()
  total()
  average()
  gradeOf()
  printReport()

Each task becomes a function: a reusable block with a name. Once you see why the pieces should be separate, the syntax below is just how you write one.

Why Use Functions?

  • Avoid code duplication
  • Make code readable and organized
  • Easier to test and debug
  • Break complex problems into smaller pieces

Function Syntax

return_type function_name(parameters) {
    // body
    return value;  // if not void
}

Examples

void greet() {
    std::cout << "Hello!" << std::endl;
}

int add(int a, int b) {
    return a + b;
}

double calculateArea(double width, double height) {
    return width * height;
}

The Call Stack

Each time a function is called, a new frame is pushed onto the call stack. When it returns, its frame is popped and control goes back to the caller.

The call stack grows as one function calls anotherCall stack (top = currently running)main()callsgreet()callsprintName()
Frames stack up as functions call one another.

Function Declaration vs Definition

// Declaration (prototype) — tells compiler about function
int add(int a, int b);  // No body

// Definition — actual implementation
int add(int a, int b) {
    return a + b;
}

Prototypes are placed before main(), definitions after main().

Scope

int x = 10;  // Global variable
void foo() {
    int x = 20;  // Local variable (shadows global)
    std::cout << x;   // Prints 20
}

Always declare variables in the narrowest scope possible. Global variables make code hard to reason about and test.

Common mistakes: omitting the return statement in a non-void function, calling a function before its prototype is declared, and relying on global variables instead of parameters.

Key takeaway: Functions group reusable logic — declare prototypes before main(), define them after, and keep variables in narrow scopes.

Try it: Write a function int add(int a, int b) that returns the sum, then call it from main() and print the result.

TeachMate - Interactive learning platform for bachelor students

HomeLearnJoin Session|2 Subjects