Start learning free

LESSON 40 OF 667 · FUNCTIONS I

Returning from functions in C++

Lesson

In the previous lessons, we have used void in the function declaration. This means the function is not returning any value.

It's also possible to return a value from a function. For this, we need to specify the returnType of the function during function declaration.

Inside the function, we can use the return statement to send a value back out of a function.

The directive return can be in any place of the function. When the execution reaches it, the function stops, and the value is returned to the calling code (assigned to answer below):

int plusThree(int num) {
	return num + 3;
}

// Inside main function:
int answer = plusThree(5);
cout << answer; // Output: 8

Here, we have the data type int instead of void. This means that the function returns an int value.

plusThree takes an int argument for num and returns an int value equal to num + 3.


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


Hint
Look at the examples above if you get stuck.


STEP 1 OF 6
    Ctrl + Enter to check