Here's an example of a function:
https://codeeval.dev/gist/36fb707be72599a7f4046369141beeec
A function declaration declares a function but doesn't provide an implementation:
// declares a function add2 that takes a a single int argument named i
// and returns a result of type int
int add2(int i);
In the example above, the int add2(int i)
function declares the following to the compiler:
int
.add2
.int
.i
.The argument name is optional; the declaration for the function could also be the following:
int add2(int); // in a declaration, name of the argument is optional
Per the one-definition rule, a function with a certain type signature can only be declared or defined once in an entire C++ code base visible to the C++ compiler. In other words, functions with a specific type signature cannot be re-defined – they must only be defined once. Thus, the following is not valid C++:
int add2(int i); // The compiler will note that add2 is a function (int) -> int
int add2(int j); // This is an error because add2 function (int) -> int has already been declared
If a function returns nothing, its return type is written as void
. If it takes no parameters, the parameter list should be empty.
void do_something(); // The function takes no parameters, and doesn't return anything.
A function definition defines the body of the function:
int add2(int i)
{
// define variable j whose value is i + 2
int j = i + 2;
// return variable j as a result of function add2
return j;
}