Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

function
c++
communitycreator

How to create a function in C++

Onyejiaku Theophilus Chidalu

Overview

A function in C++ is a block of code that runs or performs a task when it is called. A data is passed to this function, known as the parameter(s) of the function.

Functions are used to perform operations and they are really important when we try to reuse a code. In simpler terms, once a function is defined or created in a code, it can be used many times in the same code.

Creating a function

To create a function in C++, we write or specify the name of the function followed by parenthesis ().

Syntax of a function in C++

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

In the above syntax, myFunction() is the name of the function we created. void means that the function does not return a value. // block of code to be executed is a comment but will normally take the block of code we wish to perform using the function.

Calling a function

When we create a function, it is saved in order to be used later in a code whenever it is called. To call a function in C++, we write the name of the function followed by two parentheses () and a semicolon ;.

Example

In the below code, we’ll create a function myFunction(), and use this function to perform a simple task: to print Hello World when we call it later on in the code.

#include <iostream>
using namespace std;

// creating a function 
void myFunction() {
  cout << "Hello World";
}

int main() {
  // calling the function 
  myFunction();
  
  return 0;
}
Creating and calling a function

Explanation

  • Line 5: We create a function named myFunction().
  • Line 6: We call the function to print the block of code Hello World whenever we call it.
  • Line 11: We call the function.

Note: A function defined by a user, such as the function we created above, myFunction(), should come before the main() function. Otherwise, it will result in an error.

Example

#include <iostream>
using namespace std;
// calling the main() function before the user-defined function 
int main() {
  myFunction();
  return 0;
}


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

// this will return an error message
Creating a user-defined function after the main() function

The above code shows that when we declare the main() function before a user-defined function, it ultimately returns an error message.

RELATED TAGS

function
c++
communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring