Industrial manufacturing
Industrial Internet of Things | Industrial materials | Equipment Maintenance and Repair | Industrial programming |
home  MfgRobots >> Industrial manufacturing >  >> Industrial programming >> C Language

C++ Functions Explained with Practical Code Examples

What Is a Function in C++?

A function in C++ is a self‑contained block of code that accepts input, processes it, and returns a result. By encapsulating repeated tasks in a function, developers avoid duplicating code and can easily reuse logic across a program by supplying different parameters.

Every C++ application contains at least one function: main(). The rest of the code can be organized into smaller, purpose‑specific functions, improving readability and maintainability.

Modern C++ provides a rich set of built‑in functions in the standard library. You can call these directly without writing the implementation yourself.

In this tutorial you will discover:

Why Use Functions?

Functions offer multiple advantages:

Built‑in Functions

Standard library functions are pre‑defined and ready to use. You simply invoke them; you do not need to provide an implementation.

Example 1: Using sqrt() from cmath

#include <iostream>
#include <cmath>
using namespace std;

int main() {
    double num, squareRoot;
    cout << "Enter number: ";
    cin >> num;
    squareRoot = sqrt(num);
    cout << "The square root of " << num << " is: " << squareRoot;
    return 0;
}

Output:

C++ Functions Explained with Practical Code Examples

Screenshot of the running program:

C++ Functions Explained with Practical Code Examples

Code Breakdown:

  1. Include iostream for input/output functions.
  2. Include cmath to access the sqrt() function.
  3. Use the std namespace to avoid prefixing standard names.
  4. Define the main() function where program logic resides.
  5. Declare num and squareRoot as double.
  6. Prompt the user for a number.
  7. Read the user’s input into num.
  8. Call sqrt() to compute the square root of num.
  9. Display the result.
  10. Return 0 to signal successful execution.

User‑Defined Functions

Developers can create custom functions to encapsulate logic that is specific to their application.

Example 2: A Simple Greeting Function

#include <iostream>
using namespace std;

void sayHello() {
    cout << "Hello!";
}

int main() {
    sayHello();
    return 0;
}

Output:

C++ Functions Explained with Practical Code Examples

Code screenshot:

C++ Functions Explained with Practical Code Examples

Explanation:

  1. Include iostream for console I/O.
  2. Bring the std namespace into scope.
  3. Define sayHello(), a function that prints a greeting.
  4. Invoke sayHello() from main().
  5. Return 0 to indicate successful termination.

Function Declaration / Prototype

When a function is defined after main(), the compiler needs to know its signature beforehand. A prototype provides this information without the function body.

Example of a prototype:

int addFunc(int, int);

Only the return type, function name, and parameter types are required; parameter names are optional.

Function Definition

While a prototype informs the compiler of a function’s interface, the definition supplies the executable body.

Example definition:

int addFunc(int num1, int num2) {
    return num1 + num2;
}

Syntax

return_datatype function_name(parameter_list) {
    // function body
}

Key components:

Calling a Function

To execute a function, you must invoke it by name and provide any required arguments.

Example call:

int result = addFunc(3, 5);

Passing Arguments

Arguments must match the function’s parameter list in both count and type. Mismatched arguments trigger compile‑time errors.

Default parameter values can be specified, allowing callers to omit those arguments.

Example 3: Adding Two Numbers with a Prototype

#include <iostream>
using namespace std;

int addFunc(int, int); // prototype

int main() {
    int x, y, sum;
    cout << "Enter two numbers: ";
    cin >> x >> y;
    sum = addFunc(x, y);
    cout << "The sum of " << x << " and " << y << " is: " << sum;
    return 0;
}

int addFunc(int num1, int num2) {
    return num1 + num2;
}

Output:

C++ Functions Explained with Practical Code Examples

Screenshot:

C++ Functions Explained with Practical Code Examples

Explanation:

  1. Include necessary headers and namespaces.
  2. Declare a prototype for addFunc().
  3. Read two integers from the user.
  4. Invoke addFunc() with those values and store the result.
  5. Display the sum.
  6. Define addFunc() after main(), providing the logic to add the two parameters.

Summary

C Language

  1. Mastering C++ Functions: From Basics to Advanced Usage
  2. Mastering C++ Virtual Functions: Concepts, Examples, and the Override Keyword
  3. Mastering C Functions: User-Defined and Standard Library Basics
  4. C++ do‑while Loop: Syntax, Practical Examples, and Nested Loops
  5. Mastering C++ Pointers: Concepts, Examples & Practical Applications
  6. C++ Operator Overloading – A Practical Guide with Code Examples
  7. C++ Polymorphism Explained: Practical Examples & Key Concepts
  8. Understanding C# Access Modifiers (Specifiers) with Practical Examples
  9. Master C Functions: Practical Examples of Recursion & Inline Techniques
  10. Master Python Lambda Functions: Practical Examples & Best Practices