AlgoCademy
Lesson
Code

Functions in {lang}


A function is a container for a few lines of code that perform a specific task.

Functions allow us to organize our code a lot better by breaking the code into smaller, more manageable chunks that are doing specific things.

Here's how a function definition looks like in {lang}:

returnType functionName() {
	// function body (where all the instructions are written)
}

There are two main components of a function:

1. The function header:

It consists of:

  • returnType which is the type of the value returned by the function
  • functionName is the function's name, a unique identifier we use to refer to the function
  • Parentheses (()). We'll learn more about their use in next lessons


2. The function body:

This is the code that {lang} executes whenever the function is called.

It consists of one or more {lang} statements placed inside curly brackets {} (where we have our {lang} comment).

Here's an example of a function:

void sayHello() {
	cout << "Hello World" << endl;
}

The return type of this function is void, which means the function is not returning any value. We'll learn more about this in future lessons.

Notice that we indented (added one tab before) our cout << "Hello World" << endl;.

Indentation is not mandatory like in Python, but we use it to make our code easier to read.


Calling a function

If you copy paste the code we've written above in an editor and run it, you'll notice that nothing is being printed to the console.

That's because a function declaration alone does not ask the code inside the function body to run, it just declares the existence of the function.

The code inside a function body runs, or executes, only when the function is called.

You can call or invoke a function by typing its name followed by parentheses, like this:

// Function declaration:
void sayHello() {
	cout << "Hello World" << endl;
}
	
// Function call:
sayHello(); // Output: Hello World

All of the code inside the function body will be executed every time the function is called.

In our example, each time the function is called it will print out the message Hello World on the dev console.

We can call a function as many times as it is needed.


Assignment
Follow the Coding Tutorial and let's write some functions.


Hint
Look at the examples above if you get stuck.