Skip to content

Functions

2.1 — Introduction to Functions

A function is a reusable sequence of statements designed to perform a specific job.

  • Function Call: An expression that tells the CPU to interrupt the current function and execute another.

  • Caller vs. Callee: The function initiating the call is the caller, and the function being executed is the callee.

  • Nested Functions: C++ does not allow you to define a function inside another function.


2.2 — Function Return Values

Value-returning functions send a single piece of data back to the caller.

  • Return Type: The type declared before the function name (e.g., int, double).

  • Return Statement: The return keyword indicates the specific value being sent back. Once a return statement is executed, the function exits immediately.

  • The main() function: Specifically returns an int to the Operating System. A return of 0 typically means "success."


2.3 — Void Functions

Functions with a return type of void do not return a value.

  • Purpose: Used for side effects, such as printing text to the console or modifying a global state.

  • Return in Void: You can use return; (with no value) to exit a void function early, but it is not required at the end of the function.


2.4 — Function Parameters and Arguments

Parameters and arguments allow data to be passed into a function.

  • Parameters: The variables defined in the function declaration (the "placeholders").

  • Arguments: The actual values passed to the function during a call.

  • Pass by Value: By default, C++ copies the argument's value into the parameter. Changes to the parameter inside the function do not affect the original argument.


2.5 — Introduction to Local Scope

Scope determines where an identifier can be seen and used within the code.

  • Local Variables: Variables defined inside a function body (including parameters).

  • Lifetime: Local variables are created when the function starts and destroyed when the function ends (at the closing brace }).

  • Scope: A local variable is only "in scope" from its point of definition to the end of the block.


2.6 — Why Functions are Useful?

  • Organization: Break large programs into manageable chunks.

  • Reusability: Write once, use many times.

  • Testing: Easier to isolate and debug small pieces of logic.

  • Extensibility: Easier to update a single function than to find and replace code everywhere.


2.7 — Forward Declarations and Definitions

The compiler reads code from top to bottom. If you call functionA() before it is defined, you get a compiler error.

  • Forward Declaration: Tells the compiler that an identifier exists before it is actually defined.

  • Function Prototype: A forward declaration for a function, consisting of the return type, name, and parameters (e.g., int add(int x, int y);).

  • Definition: The actual implementation (the body) of the function.


2.8 — Programs with Multiple Code Files

As programs grow, they are split into multiple .cpp files.

  • Compilation: Each .cpp file is compiled independently into an object file (.obj or .o).

  • Linking: The linker combines these object files into a single executable.

  • External Linkage: Functions define in one file can be called in another if a forward declaration is provided in the second file.


2.9 — Naming Collisions and Namespaces

A naming collision occurs when two identifiers have the same name in the same scope.

  • Namespace: A declarative region that provides a scope to the identifiers inside it.

  • The std Namespace: Everything in the C++ Standard Library lives in the std namespace.

  • Scope Resolution Operator (::): Used to tell the compiler which namespace to look in (e.g., std::cout).


2.10 — Introduction to the Preprocessor

The preprocessor is a separate program that runs on your source code before compilation.

  • Directives: Instructions starting with #.

  • #include: Tells the preprocessor to replace the directive with the entire contents of the included file.

  • #define: Creates a macro (mostly used for legacy code or conditional compilation).

  • Conditional Compilation: Using #ifdef, #ifndef, and #endif to include or exclude parts of the code.


2.11 — Header Files

Header files (.h or .hpp) are used to store forward declarations so they can be shared across multiple files.

  • Format: Header files usually contain function prototypes, but not the function bodies.

  • Include Syntax: * #include <filename>: For standard library headers (searches system directories).

    • #include "filename": For user-defined headers (searches the current directory).

2.12 — Header Guards

Naming collisions can happen if a header is included more than once in the same file.

  • Header Guards: Use preprocessor directives to ensure a header's content is only included once.

  • Structure:

    #ifndef UNIQUE_NAME_H
    #define UNIQUE_NAME_H
    // Declarations here
    #endif
    
  • #pragma once: A modern, shorter alternative supported by most compilers.


How to Design Your First Programs

  1. Define your goal: What should the program do?

  2. Define your inputs and outputs: What data do you need, and what is the result?

  3. Break it down: Use functions to handle specific sub-tasks.

  4. Write the code: Start with main() and fill in the logic.

  5. Test and Debug: Ensure each function works individually before moving on.