A function is a package of work named so we can perform the same steps as many times as needed. Once declared, it may be called from anywhere in the program using its name followed by brackets.
int add(int a, int b)
{
// Return the computed value to the caller
return a + b;
}
A function definition names a function, states its return type, parameters, and has a function body which states what it does.
Functions are defined like this:
return type (or
voidif it doesn't return a value)function name
open and close brackets, possibly with a list of parameters inside
curly brackets which define the function body.
The parameters serve as variables accessible only while the function is in operation. The caller passes values (arguments) which serve to initialize the function's parameters.
If a function simply performs a task rather than generating a value, then the void type should be used for the return type.
void greet()
{
std::cout << "Hello\n";
}
A function of void type doesn't require return, but it can be used with just a bare return; to terminate early.
void check_value(int value)
{
if (value < 0)
{
// Exit the function early when this condition is met
return;
}
std::cout << value << '\n';
}
To call a function, write its name followed by brackets which may contain arguments.
// Initialize sum with the value returned by add
int sum{add(3, 5)};
greet();
Arguments are evaluated, parameters initialized, function body executed, and return value sent back, the control transferred back to the point of call.
In the case of a void function, control is transferred to it and returned to the statement following the call once function completion.
Any side effects from arguments evaluation have occurred prior to the execution of the function body.
Functions other than void must return a value of their designated type; this is accomplished using the return statement, which simultaneously provides the value and ends execution of the function at that instant.
int square(int x)
{
return x * x;
}
Any statements appearing after return in a function will not be executed. If a function has no return when it reaches the closing brace, the resulting behavior is undefined unless the function's return type is void.
A function may not be called if the compiler doesn't know about it already.
The easiest way to ensure this is to provide the entire function definition before any calls. A declaration is necessary if this is not practical; this is also known as a prototype.
// Declare add before code needs to call it
int add(int a, int b);
int main()
{
std::cout << add(10, 20) << '\n';
}
int add(int a, int b)
{
return a + b;
}
A declaration contains the function's name and its return and parameter types. The full definition may be supplied elsewhere in the file.
Any function definition appearing later must match the declaration's parameters exactly.
One function can take two numbers, multiply them together, and return the result.
Another function can take one number, print double it, and doesn't return a value.
Both functions may be called with literals or variables; any expression of the right type may be provided for any given parameter.
A value-returning function call can be used as an argument in another expression, or its return value can be used to initialize a variable; a void function is called for its behavior, not for a return value.
#include <iostream>
int multiply(int x, int y)
{
return x * y;
}
void print_double(int n)
{
std::cout << n * 2 << '\n';
}
int main()
{
int result{multiply(6, 7)};
std::cout << "6 * 7 = " << result << '\n';
print_double(9);
int a{4};
int b{5};
std::cout << "Product is " << multiply(a, b) << '\n';
}
Functions are a useful way to group identical tasks so the repetition can be removed and the program becomes more readable. When a function call is written we're specifying what we want, and a function definition tells the program how we want it done.
Exercise: Defining and Calling FunctionsStarter code, hints and solutionOpenClose
Practice: Defining and Calling Functions
Work through the mission, reveal hints only when needed, and compare your result with the model solution.
Your challenge
Add multiply(3, 8) and print its result with a label. Explain how this returned value differs from the output performed inside print_double.
Mission checklist
- Run the starter as a baseline, then predict the change requested in Your challenge.
- Make that change in your editor; use the lesson-specific hints if you need help.
- Compile and run your answer, then compare with the worked solution and explain the result.
Starter program
This is the working baseline, not the completed answer. Compile as C++20, then make the change described above.
#include <iostream>
int multiply(int x, int y)
{
return x * y;
}
void print_double(int n)
{
std::cout << n * 2 << '\n';
}
int main()
{
int result{multiply(6, 7)};
std::cout << "6 * 7 = " << result << '\n';
print_double(9);
int a{4};
int b{5};
std::cout << "Product is " << multiply(a, b) << '\n';
}Hints
multiply returns a value, whereas print_double prints inside the function and returns void. Decide whether your new call belongs in an output expression or as a statement.
For multiply(a, b), substitute the current values of a and b into x * y. Use another small pair to predict the return value before running the call.
Worked solution
A new multiply(3, 8) call returns 24. The return value is printed by main; this differs from print_double, whose void function prints internally instead of returning a number.
#include <iostream>
int multiply(int x, int y)
{
return x * y;
}
void print_double(int n)
{
std::cout << n * 2 << '\n';
}
int main()
{
int result{multiply(6, 7)};
std::cout << "6 * 7 = " << result << '\n';
print_double(9);
int a{4};
int b{5};
std::cout << "Product is " << multiply(a, b) << '\n';
std::cout << "New product: " << multiply(3, 8) << '\n';
}
Example output
6 * 7 = 42
18
Product is 20
New product: 24
0 comments
No comments yet. Be the first.