Skip to main content
Back to Blog
Programming Languages
14 August 20263 min readUpdated 14 August 2026

Understanding C++ Functions

C++ Functions Functions in C++ are essential programming constructs that encapsulate a block of code, which is executed only when called. They allow for data to be passed as par...

Understanding C++ Functions

C++ Functions

Functions in C++ are essential programming constructs that encapsulate a block of code, which is executed only when called. They allow for data to be passed as parameters, enabling specific actions to be performed. This feature is crucial for code reuse, allowing developers to define code once and use it multiple times.

Creating a Function

C++ comes with predefined functions like main(), which is used to run the program. However, developers can create their own functions to perform specific tasks. To declare a function, specify its name followed by parentheses ().

Example Explanation

  • myFunction() is the designated name of the function.
  • void indicates the function does not return any value. More details on return values will be covered later.
  • Within the function body, include the code that specifies the function's operations.

Calling a Function

Functions that are declared are not immediately executed; they are invoked at a later point when needed. To call a function, write its name followed by parentheses () and a semicolon ;. In the example below, myFunction() is called to execute a print action, which can be repeated multiple times.

Function Declaration and Definition

A C++ function is composed of two main parts:

  • Declaration: Includes the return type, function name, and any parameters.
  • Definition: Contains the actual code to be executed within the function body.

Note: If a user-defined function, such as myFunction(), is declared after the main() function, an error will occur. To optimize code, it's common to see function declarations above main() and definitions below. This practice enhances code organization and readability.