2.2 — Function return values (value-returning functions) – Learn C++ (2023)

Consider the following program:

#include <iostream>int main(){// get a value from the userstd::cout << "Enter an integer: ";int num{};std::cin >> num;// print the value doubledstd::cout << num << " doubled is: " << num * 2 << '\n';return 0;}

This program is composed of two conceptual parts: First, we get a value from the user. Then we tell the user what double that value is.

Although this program is trivial enough that we don’t need to break it into multiple functions, what if we wanted to? Getting an integer value from the user is a well-defined job that we want our program to do, so it would make a good candidate for a function.

So let’s write a program to do this:

// This program doesn't work#include <iostream>void getValueFromUser(){ std::cout << "Enter an integer: ";int input{};std::cin >> input; }int main(){getValueFromUser(); // Ask user for inputint num{}; // How do we get the value from getValueFromUser() and use it to initialize this variable?std::cout << num << " doubled is: " << num * 2 << '\n';return 0;}

While this program is a good attempt at a solution, it doesn’t quite work.

When function getValueFromUser is called, the user is asked to enter an integer as expected. But the value they enter is lost when getValueFromUser terminates and control returns to main. Variable num never gets initialized with the value the user entered, and so the program always prints the answer 0.

What we’re missing is some way for getValueFromUser to return the value the user entered back to main so that main can make use of that data.

Return values

When you write a user-defined function, you get to determine whether your function will return a value back to the caller or not. To return a value back to the caller, two things are needed.

First, your function has to indicate what type of value will be returned. This is done by setting the function’s return type, which is the type that is defined before the function’s name. In the example above, function getValueFromUser has a return type of void (meaning no value will be returned to the caller), and function main has a return type of int (meaning a value of type int will be returned to the caller). Note that this doesn’t determine what specific value is returned -- it only determines what type of value will be returned.

Related content

We explore functions that return void further in the next lesson (2.3 -- Void functions (non-value returning functions)).

Second, inside the function that will return a value, we use a return statement to indicate the specific value being returned to the caller. The specific value returned from a function is called the return value. When the return statement is executed, the function exits immediately, and the return value is copied from the function back to the caller. This process is called return by value.

Let’s take a look at a simple function that returns an integer value, and a sample program that calls it:

#include <iostream>// int is the return type// A return type of int means the function will return some integer value to the caller (the specific value is not specified here)int returnFive(){ // the return statement indicates the specific value that will be returned return 5; // return the specific value 5 back to the caller}int main(){ std::cout << returnFive() << '\n'; // prints 5 std::cout << returnFive() + 2 << '\n'; // prints 7 returnFive(); // okay: the value 5 is returned, but is ignored since main() doesn't do anything with it return 0;}

When run, this program prints:

57

Execution starts at the top of main. In the first statement, the function call to returnFive is evaluated, which results in function returnFive being called. Function returnFive returns the specific value of 5 back to the caller, which is then printed to the console via std::cout.

In the second function call, the function call to returnFive is evaluated, which results in function returnFive being called again. Function returnFive returns the value of 5 back to the caller. The expression 5 + 2 is evaluated to produce the result 7, which is then printed to the console via std::cout.

In the third statement, function returnFive is called again, resulting in the value 5 being returned back to the caller. However, function main does nothing with the return value, so nothing further happens (the return value is ignored).

Note: Return values will not be printed unless the caller sends them to the console via std::cout. In the last case above, the return value is not sent to std::cout, so nothing is printed.

Tip

When a called function returns a value, the caller may decide to use that value in an expression or statement (e.g. by assigning it to a variable, or sending it to std::cout) or ignore it (by doing nothing else).

Fixing our challenge program

With this in mind, we can fix the program we presented at the top of the lesson:

#include <iostream>int getValueFromUser() // this function now returns an integer value{ std::cout << "Enter an integer: ";int input{};std::cin >> input; return input; // return the value the user entered back to the caller}int main(){int num { getValueFromUser() }; // initialize num with the return value of getValueFromUser()std::cout << num << " doubled is: " << num * 2 << '\n';return 0;}

When this program executes, the first statement in main will create an int variable named num. When the program goes to initialize num, it will see that there is a function call to getValueFromUser(), so it will go execute that function. Function getValueFromUser, asks the user to enter a value, and then it returns that value back to the caller (main). This return value is used as the initialization value for variable num.

Compile this program yourself and run it a few times to prove to yourself that it works.

Revisiting main()

You now have the conceptual tools to understand how the main function actually works. When the program is executed, the operating system makes a function call to main. Execution then jumps to the top of main. The statements in main are executed sequentially. Finally, main returns an integer value (usually 0), and your program terminates. The return value from main is sometimes called a status code (also sometimes called an exit code, or rarely a return code), as it is used to indicate whether the program ran successfully or not.

By definition, a status code of 0 means the program executed successfully.

Best practice

Your main function should return the value 0 if the program ran normally.

A non-zero status code is often used to indicate failure (and while this works fine on most operating systems, strictly speaking, it’s not guaranteed to be portable).

For advanced readers

The C++ standard only defines the meaning of 3 status codes: 0, EXIT_SUCCESS, and EXIT_FAILURE. 0 and EXIT_SUCCESS both mean the program executed successfully. EXIT_FAILURE means the program did not execute successfully.

EXIT_SUCCESS and EXIT_FAILURE are preprocessor macros defined in the <cstdlib> header:

#include <cstdlib> // for EXIT_SUCCESS and EXIT_FAILUREint main(){ return EXIT_SUCCESS;}

If you want to maximize portability, you should only use 0 or EXIT_SUCCESS to indicate a successful termination, or EXIT_FAILURE to indicate an unsuccessful termination.

We cover the preprocessor and preprocessor macros in lesson 2.10 -- Introduction to the preprocessor.

C++ disallows calling the main function explicitly.

For now, you should also define your main function at the bottom of your code file, below other functions.

A value-returning function that does not return a value will produce undefined behavior

A function that returns a value is called a value-returning function. A function is value-returning if the return type is anything other than void.

A value-returning function must return a value of that type (using a return statement), otherwise undefined behavior will result.

Related content

We discuss undefined behavior in lesson 1.6 -- Uninitialized variables and undefined behavior.

Here’s an example of a function that produces undefined behavior:

#include <iostream>int getValueFromUserUB() // this function returns an integer value{ std::cout << "Enter an integer: ";int input{};std::cin >> input;// note: no return statement}int main(){int num { getValueFromUserUB() }; // initialize num with the return value of getValueFromUserUB()std::cout << num << " doubled is: " << num * 2 << '\n';return 0;}

A modern compiler should generate a warning because getValueFromUserUB is defined as returning an int but no return statement is provided. Running such a program would produce undefined behavior, because getValueFromUserUB() is a value-returning function that does not return a value.

In most cases, compilers will detect if you’ve forgotten to return a value. However, in some complicated cases, the compiler may not be able to properly determine whether your function returns a value or not in all cases, so you should not rely on this.

Best practice

Make sure your functions with non-void return types return a value in all cases.

Failure to return a value from a value-returning function will cause undefined behavior.

Function main will implicitly return 0 if no return statement is provided

The only exception to the rule that a value-returning function must return a value via a return statement is for function main(). The function main() will implicitly return the value 0 if no return statement is provided. That said, it is best practice to explicitly return a value from main, both to show your intent, and for consistency with other functions (which will not let you omit the return value).

Functions can only return a single value

A value-returning function can only return a single value back to the caller each time it is called.

Note that the value provided in a return statement doesn’t need to be literal -- it can be the result of any valid expression, including a variable or even a call to another function that returns a value. In the getValueFromUser() example above, we returned a variable input, which held the number the user input.

There are various ways to work around the limitation of functions only being able to return a single value, which we’ll cover in future lessons.

The function author can decide what the return value means

The meaning of the value returned by a function is determined by the function’s author. Some functions use return values as status codes, to indicate whether they succeeded or failed. Other functions return a calculated or selected value. Other functions return nothing (we’ll see examples of these in the next lesson).

Because of the wide variety of possibilities here, it’s a good idea to document your function with a comment indicating what the return values mean. For example:

// Function asks user to enter a value// Return value is the integer entered by the user from the keyboardint getValueFromUser(){ std::cout << "Enter an integer: ";int input{};std::cin >> input; return input; // return the value the user entered back to the caller}

Reusing functions

Now we can illustrate a good case for function reuse. Consider the following program:

#include <iostream>int main(){int x{};std::cout << "Enter an integer: ";std::cin >> x; int y{};std::cout << "Enter an integer: ";std::cin >> y; std::cout << x << " + " << y << " = " << x + y << '\n';return 0;}

While this program works, it’s a little redundant. In fact, this program violates one of the central tenets of good programming: Don’t Repeat Yourself (often abbreviated DRY).

Why is repeated code bad? If we wanted to change the text “Enter an integer:” to something else, we’d have to update it in two locations. And what if we wanted to initialize 10 variables instead of 2? That would be a lot of redundant code (making our programs longer and harder to understand), and a lot of room for typos to creep in.

Let’s update this program to use our getValueFromUser function that we developed above:

#include <iostream>int getValueFromUser(){ std::cout << "Enter an integer: ";int input{};std::cin >> input; return input;}int main(){ int x{ getValueFromUser() }; // first call to getValueFromUser int y{ getValueFromUser() }; // second call to getValueFromUser std::cout << x << " + " << y << " = " << x + y << '\n'; return 0;}

This program produces the following output:

Enter an integer: 5Enter an integer: 75 + 7 = 12

In this program, we call getValueFromUser twice, once to initialize variable x, and once to initialize variable y. That saves us from duplicating the code to get user input, and reduces the odds of making a mistake. Once we know getValueFromUser works, we can call it as many times as we desire.

This is the essence of modular programming: the ability to write a function, test it, ensure that it works, and then know that we can reuse it as many times as we want and it will continue to work (so long as we don’t modify the function -- at which point we’ll have to retest it).

Best practice

Follow the DRY best practice: “don’t repeat yourself”. If you need to do something more than once, consider how to modify your code to remove as much redundancy as possible. Variables can be used to store the results of calculations that need to be used more than once (so we don’t have to repeat the calculation). Functions can be used to define a sequence of statements we want to execute more than once. And loops (which we’ll cover in a later chapter) can be used to execute a statement more than once.

As an aside…

The opposite of DRY is WET (“Write everything twice”).

Conclusion

Return values provide a way for functions to return a single value back to the function’s caller.

Functions provide a way to minimize redundancy in our programs.

Quiz time

Question #1

Inspect (do not compile) each of the following programs. Determine what the program will output, or whether the program will generate a compiler error.

Assume you have “treat warnings as errors” turned off.

1a)

#include <iostream>int return7(){ return 7;}int return9(){ return 9;}int main(){ std::cout << return7() + return9() << '\n'; return 0;}

Show Solution

1b)

#include <iostream>int return7(){ return 7; int return9() { return 9; }}int main(){ std::cout << return7() + return9() << '\n'; return 0;}

Show Solution

1c)

#include <iostream>int return7(){ return 7;}int return9(){ return 9;}int main(){ return7(); return9(); return 0;}

Show Solution

1d)

#include <iostream>int getNumbers(){ return 5; return 7;}int main(){ std::cout << getNumbers() << '\n'; std::cout << getNumbers() << '\n'; return 0;}

Show Solution

1e)

#include <iostream>int return 5(){ return 5;}int main(){ std::cout << return 5() << '\n'; return 0;}

Show Solution

1f) Extra credit: Will the following program compile?

#include <iostream>int returnFive(){ return 5;}int main(){ std::cout << returnFive << '\n'; return 0;}

Show Solution

Question #2

What does “DRY” stand for, and why is it a useful practice to follow?

Show Solution

Next lesson2.3Void functions (non-value returning functions)Back to table of contentsPrevious lesson2.1Introduction to functions

FAQs

What is a value returning function in C++? ›

A function that returns a value is called a value-returning function. A function is value-returning if the return type is anything other than void . A value-returning function must return a value of that type (using a return statement), otherwise undefined behavior will result. Related content.

Can a function return 2 values in C++? ›

We can return more than one values from a function by using the method called “call by address”, or “call by reference”. In the invoker function we will use two variables to store the results, and the function will take pointer type data. So we have to pass the address of the data.

Can we return function from function in C++? ›

Return Array from Functions in C++

C++ does not allow to return an entire array as an argument to a function. However, you can return a pointer to an array by specifying the array's name without an index.

What is the best way to return two values in C++? ›

The Best Way to Return Multiple Values from a C++17 Function
  1. Using output parameters: auto output_1( int &i1) { i1 = 11; return 12; }
  2. Using a local structure: auto struct_2() { struct _ { int i1, i2; }; return _{21, 22}; }
  3. Using an std::pair : auto pair_2() { return std::make_pair(31, 32); }
  4. Using an std::tuple :
Jun 30, 2022

What is a value return function? ›

A return is a value that a function returns to the calling script or function when it completes its task. A return value can be any one of the four variable types: handle, integer, object, or string. The type of value your function returns depends largely on the task it performs.

How do you write a value returning function? ›

To return a value from a function, you must include a return statement, followed by the value to be returned, before the function's end statement. If you do not include a return statement or if you do not specify a value after the keyword return, the value returned by the function is unpredictable.

Can a function return more than 1 value C++? ›

A C++ function can return only one value. However, you can return multiple values by wrapping them in a class or struct. Or you could use std::tuple , if that is available with your compiler. If you don't know in advance how many values you're going to return, a std::vector or a similar container is your best bet.

Can a function return 2 functions? ›

No, you can not have two returns in a function, the first return will exit the function you will need to create an object.

Can a function return 2 variables? ›

Multiple values cannot be returned from a function in JavaScript but multiple values can be stored in an array or in an object and then the array or the object can be returned.

Do all functions have return value C++? ›

In C++, a function which is defined as having a return type of void , or is a constructor or destructor, must not return a value. If a function is defined as having a return type other than void , it should return a value.

What is function in C++ with example? ›

A function definition provides the actual body of the function. The C++ standard library provides numerous built-in functions that your program can call. For example, function strcat() to concatenate two strings, function memcpy() to copy one memory location to another location and many more functions.

Can a function return a function? ›

A function can return a function in Python because functions are treated as first-class objects. This means that you can assign a function to a variable, pass it as an argument to another function, or use it as a return value in a function. Defining functions in other functions and returning functions are all possible.

What is return 2 C++? ›

In your case, it appears that the statements are taken from the body of a function returning an int (or a related type convertible from int ). So, return 2 simply returns the value 2.

What is the return type of operator ++ in C++? ›

Example 2: ++ Operator (Unary Operator) Overloading

This is because the return type of our operator function is void .

Which function is used to return the next character in C++? ›

The getchar() function is equivalent to a call to getc(stdin). It reads the next character from stdin which is usually the keyboard. It is defined in <cstdio> header file.

What are the 4 types of functions? ›

Constant Function: The polynomial function of degree zero. Linear Function: The polynomial function of degree one. Quadratic Function: The polynomial function of degree two. Cubic Function: The polynomial function of degree three.

What is return type in C++ with example? ›

The return type, which specifies the type of the value that the function returns, or void if no value is returned. In C++11, auto is a valid return type that instructs the compiler to infer the type from the return statement. In C++14, decltype(auto) is also allowed.

Why do we use return in functions? ›

A return statement ends the execution of a function, and returns control to the calling function. Execution resumes in the calling function at the point immediately following the call. A return statement can return a value to the calling function.

What can value returning functions return? ›

By definition, a value-returning function returns a single value; this value is returned via the return statement. Use void functions with reference parameters to return (modify) more than one value.

How many values can a function return? ›

A function can only return a single object.

What is the minimum number of values a function can return in C++? ›

However, C++ functions either return one value or no value.

Can you have multiple return 0 in C++? ›

You can have multiple return statements and it should not matter, if you are returning the same variable. However if you have multiple variables in your function and you return then differently depending on the code flow the compiler cannot perform such optimisation.

Can function return only one value in C? ›

The correct answer is Single value. Concept: A function in C can be called either with arguments or without arguments. Always, Only one value can be returned from a function.

Do all functions return a value? ›

Some functions don't return a significant value, but others do. It's important to understand what their values are, how to use them in your code, and how to make functions return useful values.

Can a function return one or more values? ›

You can return multiple values from a function using either a dictionary, a tuple, or a list. These data types all let you store multiple values. There is no specific syntax for returning multiple values, but these methods act as a good substitute.

How do you call a function that returns another function? ›

In JavaScript, you can call a function that returns another function by first assigning the returned function to a variable and then calling it using the variable name, followed by parentheses.

When a function returns 2 or more values it is actually returning? ›

In Python, when returning multiple values separated by commas, all the values listed are actually wrapped inside a data type known as a tuple , which looks like (1, 2, 3) . That tuple is returned, containing each value.

Can a function have two values? ›

By definition, no. A function maps every X value in the valid domain to only a single Y value. "In mathematics, a function is a relation between a set of inputs and a set of permissible outputs with the property that each input is related to exactly one output".

How to do functions with two variables? ›

A function of two variables is a function, that is, to each input is associated exactly one output.
  1. The inputs are ordered pairs, (x,y). The outputs are real numbers (each output is a single real number). ...
  2. The function can be written z=f(x,y).
  3. We will often now call the familiar y=f(x) a function of one variable.

How many types of returning values are present in C++? ›

How many types of returning values are present in c++? Explanation: The three types of returning values are return by value, return by reference and return by address.

Which function has return value and no arguments C++? ›

Example 2: No arguments passed but a return value

In the above program, prime() function is called from the main() with no arguments. prime() takes a positive integer from the user. Since, return type of the function is an int , it returns the inputted number from the user back to the calling main() function.

Which of the following will not return a value in C++? ›

1. Which of the following will not return a value? Explanation: Because void represents an empty set of values so nothing will be return.

What are popular C++ functions? ›

Some common library functions in C++ are sqrt() , abs() , isdigit() , etc. In order to use library functions, we usually need to include the header file in which these library functions are defined.

What is the main function in C++? ›

The main function serves as the starting point for program execution. It usually controls program execution by directing the calls to other functions in the program.

What is main function in C++ simple? ›

The function named main is a special function in all C++ programs; it is the function called when the program is run. The execution of all C++ programs begins with the main function, regardless of where the function is actually located within the code.

Can a function return a variable? ›

As you already know a function can return a single variable, but it can also return multiple variables.

How do you not return a value in a function? ›

If a function is defined as having a return type of void , it should not return a value. In C++, a function which is defined as having a return type of void , or is a constructor or destructor, must not return a value. If a function is defined as having a return type other than void , it should return a value.

Can a function not return? ›

A function that does not return a value is called a non-value returning function (or a void function). A void function will automatically return to the caller at the end of the function. No return statement is required.

Do I need return in C++? ›

tl;dr: C++ functions do not require a return keyword in them to be well-formed and compile, though it will likely cause undefined behaviour. Your specific compiler may also warn or error. In almost all cases, you want a return keyword.

Is C++ return by value? ›

C++ functions can return by value, by reference (but don't return a local variable by reference), or by pointer (again, don't return a local by pointer). When returning by value, the compiler can often do optimizations that make it equally as fast as returning by reference, without the problem of dangling references.

What is exit vs return in C++? ›

return is a statement that returns the control of the flow of execution to the function which is calling. Exit statement terminates the program at the point it is used.

What is the difference between void function and value returning function? ›

Void functions are created and used just like value-returning functions except they do not return a value after the function executes. In lieu of a data type, void functions use the keyword "void." A void function performs a task, and then control returns back to the caller--but, it does not return a value.

What is a value returning function quizlet? ›

What is a value returning function? a function that returns a value back to the part of the program that called it.

Where is the return value of a function stored C++? ›

Where is it stored? Well, it isn't stored. It actually gets erased from memory. When we call a function, the function executes its code and after the return, that particular function call gets wiped out from working memory ( the browser is in charge of the cleanup task).

What is no return value function in C++? ›

A function that does not return a value is called a non-value returning function (or a void function). A void function will automatically return to the caller at the end of the function. No return statement is required.

What are the different types of returning values in C++? ›

How many types of returning values are present in c++? Explanation: The three types of returning values are return by value, return by reference and return by address.

When a function returns two values? ›

No, you can not have two returns in a function, the first return will exit the function you will need to create an object.

How many value is returned by a function? ›

A function can only return a single object.

What is a function whose return value depends on the value? ›

A closure is a function, whose return value depends on the value of one or more variables declared outside this function.

Which keyword is used to return value from the function definition? ›

Definition and Usage

The return keyword finished the execution of a method, and can be used to return a value from a method.

How many values can a function return in C++? ›

A C++ function can return only one value.

Does a function always return a value? ›

Some functions don't return a significant value, but others do. It's important to understand what their values are, how to use them in your code, and how to make functions return useful values.

Do C++ functions need return type? ›

The required parts of a function declaration are: The return type, which specifies the type of the value that the function returns, or void if no value is returned. In C++11, auto is a valid return type that instructs the compiler to infer the type from the return statement.

Do void functions need a return statement in C++? ›

For a function of return type void , a return statement is not strictly necessary. If the end of such a function is reached without encountering a return statement, control is passed to the caller as if a return statement without an expression were encountered.

References

Top Articles
Latest Posts
Article information

Author: Frankie Dare

Last Updated: 24/01/2024

Views: 6422

Rating: 4.2 / 5 (53 voted)

Reviews: 92% of readers found this page helpful

Author information

Name: Frankie Dare

Birthday: 2000-01-27

Address: Suite 313 45115 Caridad Freeway, Port Barabaraville, MS 66713

Phone: +3769542039359

Job: Sales Manager

Hobby: Baton twirling, Stand-up comedy, Leather crafting, Rugby, tabletop games, Jigsaw puzzles, Air sports

Introduction: My name is Frankie Dare, I am a funny, beautiful, proud, fair, pleasant, cheerful, enthusiastic person who loves writing and wants to share my knowledge and understanding with you.