C++ Functions with Program Examples

โšก Smart Summary

Functions in C++ group related statements into reusable named blocks that take input, process it, and return output. Programs combine built-in library functions and user-defined functions, each declared, defined, and called to avoid repeating code.

  • ๐Ÿงฉ What it is: A function groups statements that take parameters, process them, and return a value, running a common task from one block.
  • ๐Ÿ“š Built-in functions: The C++ standard library ships ready functions such as sqrt() that you call directly without writing them.
  • ๐Ÿ› ๏ธ User-defined functions: Programmers create their own functions, name them uniquely, and invoke that code from anywhere in the program.
  • ๐Ÿ“ Declaration and definition: A prototype declares the return type, name, and argument types; the definition supplies the function body.
  • ๐Ÿ“ž Call and arguments: Calling a function runs its body; arguments must match parameters in number and type, and defaults are allowed.
  • ๐Ÿค– AI assistance: GitHub Copilot and similar assistants scaffold C++ function signatures, bodies, and calls from a short comment.

C++ Functions

What is a Function in C++?

A function in C++ refers to a group of statements that takes input, processes it, and returns an output. The idea behind a function is to combine common tasks that are done repeatedly. If you have different inputs, you will not write the same code again. You will simply call the function with a different set of data called parameters.

Each C++ program has at least one function, the main() function. You can divide your code into different functions. This division should be such that every function does a specific task.

There are many built-in functions in the C++ standard library. You can call these functions within your program.

Why use functions?

There are numerous benefits associated with the use of functions. These include:

  • Each function puts related code together. This makes it easier for programmers to understand code.
  • Functions make programming easier by eliminating code repetition.
  • Functions facilitate code reuse. You can call the same function to perform a task at different sections of the program or even outside the program.

Built-in Functions

In C++, library functions are built-in C++ functions. To use these functions, you simply invoke/call them directly. You do not have to write the functions yourself.

Example 1:

#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:

Output of the C++ built-in sqrt() function example

Here is a screenshot of the code:

C++ code calling the built-in sqrt() function from cmath

Code Explanation:

  1. Include the iostream header file in our program to use its functions.
  2. Include the cmath library to use its functions. We want to use the function sqrt() defined in it.
  3. Include the std namespace in our code to use its classes without calling it.
  4. Call the main() function. The program logic should be added within the body of this function.
  5. Declare two double variables, num, and squareRoot.
  6. Print some text on the console. The text asks the user to enter a number.
  7. Read user input from the keyboard. The input will become the value of variable num.
  8. Call the library function sqrt(), which calculates the square root of a number. We passed the parameter num to the function, meaning it will calculate the square root of num. This function is defined in the cmath library.
  9. Print the number entered by the user, its square root, and some other text on the console.
  10. The program must return value upon successful completion.
  11. End of the body of the main() function.

User-Defined Functions

C++ allows programmers to define their own functions. The purpose of the function is to group related code. The code is then given a unique identifier, the function name.

The function can be called/invoked from any other part of the program. It will then execute the code defined within its body.

Example 2:

#include <iostream>
using namespace std;

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

int main() {

	sayHello();

	return 0;
}

Output:

Output of the C++ user-defined sayHello() function

Here is a screenshot of the code:

C++ code defining and calling a user-defined function

Code Explanation:

  1. Include the iostream header file in our program to use its functions.
  2. Include the std namespace in our code to use its classes without calling it.
  3. Create a user-defined function named sayHello().
  4. Print some text on the console when the sayHello() function is called.
  5. End of the body of the sayHello() function.
  6. Call the main() function. The program logic should be added within the body of this function.
  7. Call/invoke the function named sayHello().
  8. The program must return value upon successful completion.
  9. End of the body of the main() function.

The compiler must know a function before it is used.

Function Declaration/Prototype

If you define a user-defined function after the main() function, the C++ compiler will return an error. The reason is that the compiler does not know the details of the user-defined function. The details include its name, the types of arguments, and their return types.

In C++, the function declaration/prototype declares a function without a body. This gives the compiler details of the user-defined function.

In the declaration/prototype, we include the return type, the function name, and argument types. The names of arguments are not added. However, adding the argument names generates no error.

C++ function declaration/prototype syntax diagram

Function Definition

The purpose of the function declaration is to tell the C++ compiler about the function name, the return type, and parameters. A function definition tells the C++ compiler about the function body.

C++ function definition structure diagram

Syntax

return_datatype function_name( parameters) {
   function body 
}

From the above, a function definition has the function header and body. Here is an explanation of the parameters:

  • return_datatype- Some functions return value. This parameter denotes the data type of the return value. Some functions do not return value. In that case, the value of this parameter becomes void.
  • function_name- This is the name of the function. The function name and parameters form the function signature.
  • Parameters- This is the type, the order, and the number of function parameters. Some functions do not have parameters.
  • function body- these are statements defining what the function will do.

Function Call

For a function to perform the specified task and return output, it must be called. When you call a function, it executes the statements added within its body.

A function is called by its name. If the function takes parameters, their values should be passed during the call. If the function takes no parameters, do not pass any value during the call.

C++ function call syntax diagram

Passing Arguments

In C++, an argument/parameter is the data passed to a function during its call. The values must be initialized to their respective variables.

When calling a function, the arguments must match in number. This means the values you pass must be equal to the number of parameters. Again, the values must also match the parameters in terms of type. If the first parameter is an integer, the value passed to it must be an integer.

One can assign default values to function parameters. If you do not pass a value for the parameter during the function call, the default value will be used.

Example 3: How to Write and Call a Function

#include <iostream>
using namespace std;
int addFunc(int, int);
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) {
	int addFunc;
	addFunc = num1 + num2;
	return addFunc;
}

Output:

Output of the C++ addFunc() function returning a sum

Here is a screenshot of the code:

C++ code passing arguments to the addFunc() function

Code Explanation:

  1. Include the iostream header file in our program to use its functions.
  2. Include the std namespace in our code to use its classes without calling it.
  3. Declare a function named addFunc() that takes two integer parameters. This creates the function prototype.
  4. Call the main() function. The program logic should be added within the body of this function.
  5. Declare three integer variables, x, y, and sum.
  6. Print some text on the console. The text asks the user to enter two numbers.
  7. Read the user input from the keyboard. The user should enter two numbers for variables x and y, separated by space.
  8. Call the function addFunc() and passing to it the parameters x and y. The function will operate on these parameters and assign the output to the variable sum.
  9. Print the values of variables x, y, and sum on the console alongside other text.
  10. The function must return value upon successful completion.
  11. End of the body of the main() function.
  12. Function definition. We are defining the function addFunc(). We will state what the function will do within its body, the { }.
  13. Declaring an integer variable named addFunc.
  14. Adding the values of parameters num1 and num2 and assigning the result to variable addFunc.
  15. The addFunc() function should return the value of addFunc variable.
  16. End of the function body, that is, function definition.

FAQs

Call by value copies the argument, so changes inside the function do not affect the original. Call by reference passes the variable with an ampersand, letting the function modify the caller’s value directly. C++ defaults to call by value.

Function overloading lets several functions share one name but differ in the number or type of their parameters. The compiler picks the correct version from the arguments you pass, improving readability for related operations.

An inline function asks the compiler to insert its body at each call site instead of making a normal call. This can cut overhead for tiny functions, though the compiler may ignore the hint.

A recursive function calls itself, breaking a problem into smaller subproblems. It needs a base case that stops the recursion; otherwise the calls repeat forever and overflow the stack. Factorial is a classic example.

You pass the parameter as a pointer or sized array and usually send its length separately, because the array decays to a pointer. See passing arrays in C++ functions for complete worked examples.

A function returns one value directly, but you can return several using output reference parameters, a struct, a std::pair, a std::tuple, or a std::vector. Structured bindings then unpack the returned tuple at the call site.

Yes. AI coding assistants turn a plain-language comment into a complete C++ function, suggesting the signature, body, and return type. They also refactor long functions, though you should review the generated logic.

GitHub Copilot autocompletes C++ function definitions, prototypes, and calls from your comments or names, proposes overloads, and drafts unit tests. It uses referenced headers for context, but every suggestion still needs review.

Summarize this post with: