C++ Functions: Complete Guide Covering Every Aspect - w9school

C++ provides some pre-defined functions, such as main() , which is used to execute code. But you can also create your own functions to perform certain actions.

C++ Functions: Complete Guide Covering Every Aspect - w9school

C++ Functions

The term "function" refers to a section of code that runs only at the time it's invoked.

You can input information, also known as parameters, to the function.

Functions perform specific actions. They are crucial for the reuse of code. Create the code once and reuse it multiple times.

How to Use C++ Functions

Functions are an invaluable programming tool that enable you to structure your program into segments that accomplish one specific task, making the code simpler to read, edit, and debug.

Functions can be used in programs for almost every purpose imaginable, from performing simple calculations and text generation, to allocating memory. To use functions effectively in your code, first declare them. After declaring, simply call them whenever required by calling them out in your code.

There are two primary types of C++ functions: library and user-defined. Library functions allow you to draw upon premade functions for use in your program; user-defined ones enable more complex logic implementation and allow greater customization.

To define a function, you must create a prototype and define its body. Furthermore, you should provide details regarding the function's name, return data type and parameter types; some functions do not return anything at all and in such instances must use void as the return type to indicate this fact.

Functions must include a return statement in order to inform their calling programs of their results of execution. A function's return statement should always return an integer value that complies with its return data type (if any).

When creating user-defined functions, it is recommended to give them names that clearly describe their task. This will make it easier for future programmers to comprehend what your function does. Also, keep the length of each function to seven lines or less for best results.

You have two options for passing arguments to functions: reference or value. By default, C++ uses call-by-value which copies actual arguments into formal parameters; this ensures any changes made to function parameters don't change how arguments were passed in call-by-value method.

Below is an example of a user-defined function to calculate the factorial of any given number, using three integer parameters x, y, and sum as input parameters and returning their sum as its return value. It can then be called from within your program's main() function for use.

In our previous example, we read two input values from the user and then called the addFunction() function to calculate their sum. The result of the function was then printed out along with other text in our console.

As we are writing our own programs, we need to decide how many functions and data will need to be stored within it. This will play an integral role in how much time we will spend writing the program as well as maintaining it after it has been written; so it is crucial that this decision is made as early in the process as possible. For instance, if creating an app with multiple users it would be prudent to break out functionality into separate functions.

Create a Function

C++ provides some pre-defined functions, like the main(), which can be used to run instructions. You can also write your own functions that perform specific actions.

To construct (often called declaration) the function that is named, you must specify what the purpose of the program is followed by the parentheses ():

Syntax

void myFunction() {
  // code to be executed
}

Example Explained

  • myFunction() is the name of the function.
  • "void" is a reference to the fact that the function doesn't provide an outcome value. We will discuss return values in the next chapter.
  • Within the functions (the body), include code that specifies what the function will do.

Call a Function

Declared functions cannot be executed immediately. They're "saved for later use" and are executed later, after the time comes to call them.

To invoke a function, compose the name of the function and then add two parentheses () and a semicolon ;

The following illustration myFunction() is used to print the text (the action) when it's called

Example

Within the main the function, you can use myFunction():

// Create a function
void myFunction() {
  cout << "I just got executed!";
}

int main() {
  myFunction(); // call the function
  return 0;
}

// Outputs "I just got executed!"

A function may be invoked multiple times:

Example

void myFunction() {
  cout << "I just got executed!\n";
}

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

// I just got executed!
// I just got executed!
// I just got executed!

Function Declaration and Definition

C++ functions are a C++ function consist of two components:

  • declaration: the return type, what the program's name is and the parameters (if there are any)
  • Defined: the body of the function (code to be executed)
void myFunction() { // declaration
  // the body of the function (definition)
}

Notice: If a user-defined function, like myFunction() is declared within the primary() function,

An error could occur:

Example

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

void myFunction() {
  cout << "I just got executed!";
}

// Error

 

It is however, possible to separate the declaration from functions definition to improve the efficiency of code.

It is common to see C++ programs that contain function declarations over the main(), and function definitions beneath the main(). This makes the code more organized and more readable:

Example

// Function declaration
void myFunction();

// The main method
int main() {
  myFunction();  // call the function
  return 0;
}

// Function definition
void myFunction() {
  cout << "I just got executed!";
}

C++ Function Parameters

Parameters and Arguments

Information can be provided to functions via an parameter. Parameters function as variables within the function.

Parameters are defined in the function's name within the parentheses. You can include any number of parameters you like, but break them up by a comma

Syntax

void functionName(parameter1, parameter2, parameter3) {
  // code to be executed
}

The following example contains the function which takes the string known as "fname" as a parameter. If the function gets invoked, we send the first name, which is used in this function in order to display out the full name:

Example

void myFunction(string fname) {
  cout << fname << " Refsnes\n";
}

int main() {
  myFunction("Liam");
  myFunction("Jenny");
  myFunction("Anja");
  return 0;
}

// Liam Refsnes
// Jenny Refsnes
// Anja Refsnes

If an parameter is given to the function, it's called"an" argument. In the above example the parameter fname is an argument that is a parameter, whereas Liam, Jenny and Anja are arguments.

C++ Default Parameters

Default Parameter Value

It is also possible to use the default value for parameter with the use of an equals symbol ( =).

If you call the function without an argument, it is using its default setting ("Norway"):

Example

void myFunction(string country = "Norway") {
  cout << country << "\n";
}

int main() {
  myFunction("Sweden");
  myFunction("India");
  myFunction();
  myFunction("USA");
  return 0;
}

// Sweden
// India
// Norway
// USA

A parameter that is set to default value is commonly referred to as an "optional parameter". In the example above, country is an optional parameter. "Norway" is the default value.

C++ Multiple Parameters

Multiple Parameters

In your function, you have the ability to include as many parameters as you'd like:

Example

void myFunction(string fname, int age) {
  cout << fname << " Refsnes. " << age << " years old. \n";
}

int main() {
  myFunction("Liam", 3);
  myFunction("Jenny", 14);
  myFunction("Anja", 30);
  return 0;
}

// Liam Refsnes. 3 years old.
// Jenny Refsnes. 14 years old.
// Anja Refsnes. 30 years old.

Note that when you're dealing with several parameters, your function must contain exactly the same amount of parameters as are parameters. Additionally, the arguments should be sent in the same order.

C++ The Return Keyword

Return Values

The"void" keyword, which was used in the previous examples, signifies that the function must not return any value. If you would like this function to return an actual value, you can choose the kind of data (such like string, int, string or.) instead of empty and also utilize to use the return keyword in the function:

Example

int myFunction(int x) {
  return 5 + x;
}

int main() {
  cout << myFunction(3);
  return 0;
}

// Outputs 8 (5 + 3)

This example calculates the sum of a formula with 2 parameters:

Example

int myFunction(int x, int y) {
  return x + y;
}

int main() {
  cout << myFunction(5, 3);
  return 0;
}

// Outputs 8 (5 + 3)

You could also save the results in a variable

Example

int myFunction(int x, int y) {
  return x + y;
}

int main() {
  int z = myFunction(5, 3);
  cout << z;
  return 0;
}
// Outputs 8 (5 + 3)

C++ Functions - Pass By Reference

Pass By Reference

In the examples on the previous page, we made use of normal variables to pass parameters to functions. It is also possible to use an explicit references in the direction of your function. This is useful for when you want to alter the value of arguments:

Example

void swapNums(int &x, int &y) {
  int z = x;
  x = y;
  y = z;
}

int main() {
  int firstNum = 10;
  int secondNum = 20;

  cout << "Before swap: " << "\n";
  cout << firstNum << secondNum << "\n";

  // Call the function, which will change the values of firstNum and secondNum
  swapNums(firstNum, secondNum);

  cout << "After swap: " << "\n";
  cout << firstNum << secondNum << "\n";

  return 0;
}

C++ Pass Array to a Function

Pass Arrays as Function Parameters

It is also possible to send arrays to an application:

Example

void myFunction(int myNumbers[5]) {
  for (int i = 0; i < 5; i++) {
    cout << myNumbers[i] << "\n";
  }
}

int main() {
  int myNumbers[5] = {10, 20, 30, 40, 50};
  myFunction(myNumbers);
  return 0;
}

Example Explained

This function ( myFunction) uses an array as a parameters ( int myNumbers[5]) and loops through the array's elements using for loop. for loop.

In the event that this function gets invoked within the main(), we forward an array called the myNumbers array, which produces the array's elements.

Note that when you call the function, you only need to use the name of the array when passing it as an argument myFunction(myNumbers). But, the complete definition of the array is required in the parameter of the function ( int myNumbers[5]).

C++ Function Overloading

Function Overloading

With overloading functions Multiple functions may be named the same using different parameters.

Example

int myFunction(int x)
float myFunction(float x)
double myFunction(double x, double y)

Take a look at the following example, with two functions that add numbers of a different kinds:

Example

int plusFuncInt(int x, int y) {
  return x + y;
}

double plusFuncDouble(double x, double y) {
  return x + y;
}

int main() {
  int myNum1 = plusFuncInt(8, 5);
  double myNum2 = plusFuncDouble(4.3, 6.26);
  cout << "Int: " << myNum1 << "\n";
  cout << "Double: " << myNum2;
  return 0;
}

Instead of having two functions that can perform the same job it is better to overburden one.

In the following example we will overload our +Func function to handle the two variables int as well as the double:

Example

int plusFunc(int x, int y) {
  return x + y;
}

double plusFunc(double x, double y) {
  return x + y;
}

int main() {
  int myNum1 = plusFunc(8, 5);
  double myNum2 = plusFunc(4.3, 6.26);
  cout << "Int: " << myNum1 << "\n";
  cout << "Double: " << myNum2;
  return 0;
}

Notice: Multiple functions can be named the same as long as the parameters' number and/or types are distinct.

C++ Recursion

Recursion

Recursion is a method of creating a function call itself. This method allows you to reduce complex problems into smaller problems that can be solved more easily.

Recursion could be difficult to grasp. The best method to understand how it functions is to play around with it.

Recursion Example

The process of adding two numbers together is easy However, adding a number of numbers is more challenging. In the below example, recursion is used to connect a number of numbers through breaking down to the simple job of adding 2 numbers

Example

int sum(int k) {
  if (k > 0) {
    return k + sum(k - 1);
  } else {
    return 0;
  }
}

int main() {
  int result = sum(10);
  cout << result;
  return 0;
}

Example Explanation

In the event that it is called, the the sum() function is used, it adds parameters k K to the total of all numbers less in the parameter k in return with the sum. When k reaches 0 and the function returns the value 0. If the program is running, it is able to follow these steps:

10 + sum(9)
10 + ( 9 + sum(8) )
10 + ( 9 + ( 8 + sum(7) ) )
...
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + sum(0)
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + 0

Since the function doesn't start calling itself when the value of k is zero, the program ceases there and returns the results.

The programmer must be cautious when using recursion because it is quite easy to write an unfinished function that requires an excessive amount of processor or memory. However, when written correctly, recursion can be a very efficient and mathematically elegant approach to programming.

For more information, Please visit Home

What's Your Reaction?

like

dislike

love

funny

angry

sad

wow