Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Return Statement in Functions | Introduction to Functions
C++ Introduction
course content

Course Content

C++ Introduction

C++ Introduction

1. Getting Started
2. Introduction to Operators
3. Variables and Data Types
4. Introduction to Program Flow
5. Introduction to Functions

bookReturn Statement in Functions

The return statement terminates the execution of a function and returns a value of a predefined type.

h

function

copy
12345
int func() // int - predefined { int variable = 10; return variable; // variable = 10 }

If the type is specified incorrectly, the function will behave unpredictably.

cpp

main

copy
12345678910111213
#include <iostream> unsigned short func() { return -10; } //The unsigned short data type has no negative values. int main() { std::cout << func() << std::endl; }

That is, before creating a function, the type of data that it returns must be specified. Also, in C++, there are special void functions. Functions of this data type are allowed to return nothing:

cpp

first_example

cpp

second_example

copy
12345678910111213
#include <iostream> void voidFunction() { std::cout << "It's void function!" << std::endl; //function without return } int main() { voidFunction(); }

There can be multiple returns inside functions, and each one will only fire under certain conditions.

cpp

main

copy
123456789101112131415161718192021
#include <iostream> int func() { int a = 50; int b = 6; if (a > b) //if a > b, func will return a { return a; } else //otherwise func will return b { return b; } } int main() { std::cout << func() << std::endl; //func calling }

If there are two returns, the second return function will be ignored:

cpp

main

copy
12345678910111213141516
#include <iostream> int func() { int a = 50; int b = 6; return a; return b; } int main() { std::cout << func() << std::endl; //func calling }

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 5. Chapter 3
We're sorry to hear that something went wrong. What happened?
some-alt