return use in c++
The return
statement in C++ is used to exit a function and optionally return a value to the calling code. When the return
statement is encountered within a function, the function stops executing, and control is returned to the point from where the function was called.
Syntax:
return; // Used in functions returning void (no value)
return expression; // Used in functions returning a value of a specific type
Explanation:
return;
- Used in functions that do not return a value (void functions).
It simply exits the function and returns control to the calling code without any value.
return expression;
- Used in functions that have a return type other than
void
. expression
can be a variable, a constant, an operation, or any valid expression that evaluates to the function's return type.- This statement exits the function and passes the value of
expression
back to the calling code.
Example:
int add(int a, int b) {
int result = a + b;
return result; // Returns the sum of a and b
}
void showMessage() {
std::cout << "Hello, World!" << std::endl;
return; // Exits the function without returning any value
}
In the example above:
- add
is a function that takes two integers as parameters, calculates their sum, stores it in result
, and then returns result
using the return
statement.
- showMessage
is a function that simply displays "Hello, World!" and uses return;
to exit the function without returning any value because it has a return type of void
.