Defining Functions

In C++, we've already encountered a few functions. For example: size() for array size or at() for accessing a character in text. These functions were created for us. We just used them. Now we'll look at how to create such a function.

We create (define) a function in C++ by specifying the return type (e.g., void for a function that returns nothing), followed by the function name, parentheses, and a code block.

The function block already contains the statements we want the function to execute. For example:

void myFunction() {
    std::cout << "This is my function" << std::endl;
}

This creates a function that prints This is my function. If we ran this code, nothing would be printed. That's because we only defined the function but didn't call (execute) it. How to call functions will be covered in the next exercise.

Instructions

Create a function named firstFunction that will print "This is my first function!" in its code block.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

2/7

Defining Functions | Start Coder