Functions are organized structures of code that allows to perform jobs.

Move to tl;dr for summary

In C++, functions have a specific type, name, set of parameters, and statements. `type name ( parameter1, parameter2, … ) { statements }

Naming a function

If you name a function, its name must remain unique and doesn’t coincide with variable names or keywords.

  • type: the type of value it must return after the function ends.
    • If you recall the first Structure of C++, notice how main() must return 0 because the function has a type int before its name.
    • See Variables and types for more types
  • name: the name of the function
    • It must remain in ONE word, not multiple words
    • If you want to use more than one word in name, combine them in one without spaces or underscores, keep the first letter of the first word lower case, and for every word after the first word must have its first letter capitalized. (aka the camelCase naming convention)
      • get user input getUserInput
      • assign task assignTask
  • parameter1, parameter2, … : set of parameters where each consists of a type and an identifier and every parameter is separated with a comma (,)
    • ( int firstParameter, int secondParameter, int ThirdParameter, ...)
    • This setup is similar to Initializing variables without assigning a value.
  • statements: block of statements wrapped in braces {} which informs the function what to do. See Statements and flow control

For example,

#include <iostream>
using namespace std;
 
int calculateSum(int a, int b) {
	return a + b;
}
 
int main() {
	int x, y;
	cout << "Give two numbers to calculate the sum: " << endl;
	cin >> x >> y;
	cout << "The sum of " << x << " " << y << " is " << calculateSum(x, y);
	
	return 0;
}

C++ main() function

When running a C++ program, it will always call main() regardless of the order of which it is placed among other functions. Think of it as the initial function of the program before the other functions.

In the example, the main function works as follows:

  1. Declare the variables
  2. Ask the user input for two numbers with each belonging to a variable
  3. Running the calculateSum function to return the value of the sum

*arguments - The list of values or expressions that are passed to the function

Every argument inside the calling function calculateSum(x, y) assigns a value to each parameter. Parameter 1: int a value of x Parameter 2: int b value of y

Invoking a function

To invoke a function, refer to its function name and add () after it. functionName() invokes a function whereas functionName without the parameters wrapper () is referencing the function, NOT invoking a function to run

Once the function is invoked, the function runs a different set of instructions and returns a value with the proper type of the function.

In the function calculateSum, it returns the computed value x + y in integer because the function is expected to return an int

Note that by invoking the function, it pauses the program in the current line of code until it finishes running.

That’s why the message The sum of ... isn’t printed out until the function completes its program, where it finally returns a value.

Theoretically, you could assign a variable with the invoked function (as long as it has the same type)

int sum = calculateSum(x, y);

Arguments passed by values and by reference

In the previous example, we ask the user input to input two numbers and assigning those inputs to the x and y variable. The function copies the current values of those variables on the moment into the parameters.

int x = 3, y = 8, z;
z = calculateSum(x, y); // 11
x = 5, y = 10;
// the values are no longer the same from the old values
z = calculateSum(x, y); // 15

If we tried to modify the parameters inside the calling function , the variables that were called for to copy their values onto the calling function aren’t changed.

#include <iostream>
using namespace std;
 
int fakeSum(int a, int b) {
	a = 20;
	b = 10;
	return a + b;
}
 
int main() {
	int x = 3, y = 5;
	fakeSum(x, y); // 30
	
	cout << "X: " << x; // X: 20
	cout << " | ";
	cout << "Y: " << y; // Y: 10
 
	return 0;
}

If you want to reference the variables on top of the parameters instead of their copied values, you must include ampersand & after the parameter type (same as variable type).

int fakeSum(int& a, int& b) {

This function would now replaces its parameters with the variables that were referenced inside the calling function fakeSum(x, y).

Parameter 1 a is replaced with variable x parameter 2 b is replaced with variable y

Assuming that you use the same example above except that you add the ampersand on each parameter, the console will now print out: X: 20 | Y: 10

Function with no type

To make a function without a type, you use the void type. For example:

#include <iostream>
using namespace std;
 
void printMessage(string text) {
	cout << text;
}
 
int main() {
	printMessage("Hello user!");
	return 0;
}

In the example, printMessage isn’t expected to return a value because its type is void.

You could even replace the parameters list with void to expect no arguments.

#include <iostream>
using namespace std;
 
void printMessage(void) {
	cout << "Hello user!";
}
 
int main() {
	printMessage();
	return 0;
}

Specifying default values in parameters

In C++, parameters can become optional by assigning a value. If the calling function didn’t specify a value for a specific parameter, it can use that default value instead. For example:

#include <iostream>
using namespace std;
 
int multiply (int a, int b = 2) {
	return a * b;
}
 
int main() {
	cout << "Product: " << multiply(5); // Product: 10
	return 0;
}

In the example, the b value defaulted to 2 because we didn’t specify an integer for the second argument of the calling function.

If we added a second argument to the calling function multiply(5),

multiply(5, 8)

The main function now prints Product: 40 because b is given a value 8.

Declaration

In C++, the order of declaration matters. You cannot call a function before its declared.

randomFunction(); // throws an error
void randomFunction(void) {};

In many cases, you must declare the function before calling it.

void randomFunction(void) {};
randomFunction();

If you want to make your coding legible, change the parameter names into actual names that have a purpose in the function. Look into https://www.geeksforgeeks.org/cpp/naming-convention-in-c/

Here’s an example:

// Bad naming convention
void printmsg(string m) {
	cout << m;
};
 
// Good naming convention
void printMessage(string message) {
	cout << message;
};

tl;dr

summary tldr

  • syntax: type name ( parameter1, parameter2, ... ) { statements }
  • adding ampersand (&) to the parameter type links the parameter with the variable that was referred inside the calling function
  • using no ampersand to the parameter gets a copy of the variable value (if a variable is used as one of the arguments)
  • default value makes the parameter optional and use the value that was assigned next to the parameter instead
  • void type function expects no returned value
  • void parameter list expects no parameters
  • order of declaration is important for calling function