2.7 KiB
Day 3
Functions
Mathematically speaking, functions are able to take in a set of inputs and return a specific output. C++ gives you an interface by which you can create your own custom functions for purposes of modularity or recursion (where functions are necessary).
The general structure of a function is as follows:
(type that the function returns) (function name) (parameters) {
// body
}
We will now more closely analyze each of the parts of this function.
Parameters
The parameters that you put into your function are a template for how the function will work when it is actually called.
The format of the parameters must be (type) (name)
, with the parameters
separated by commas.
For instance, if you had a function to add two numbers, it would look something like this:
int add (int a, int b) {
return a+b;
}
Note that the variables a
and b
are simply aliases that you use to represent
the actual values that you place into the function when you make a call.
When you make the following function call,
cout << add(3, 2);
a
will represent 3 and b
will represent 2, and thus this code block will
print 5
. However, note that we cannot make the following call, as the
arguments are not in the types that the compiler expects them to be in:
cout << add(3, "string");
The function expects two integers, but received a string, which cannot be automatically converted to an integer for very obvious reasons.
Note that c++ will conduct automatic type conversion whenever possible to allow
the function to execute, so you can pass in a long long
or bool
and the
function should still be able to convert them into int
s.
Type
Sometimes, you want your functions to return back a value for your convenience. For instance, if you have a simple function to add two numbers, you would want to get the sum of the numbers back. In this case, you place the return type at the front of the function signature as shown above
Note that if you do wish to return a type in your function, you must return the value of that type in all possible cases, or else your compiler will throw a warning.
The void
keyword is special, as it is used for a function that does not return
any value and only has side effects.
For instance, if I were doing a floodfill traversal of a graph (where we are simply trying to find the number of disjoint regions), I would probably do the following:
void dfs(int x, int y) {
// mark as visited
// propagate
}
Note that the DFS does not actually return any real value, we simply use it for the fact that it is able to fill out the visited array.
When you use a function that returns void
, you will not actually have to
provide an explicit return
statement.