Lesson 12 · 12 of 20
Functions · C++
Write C++ functions with a return type and parameters, use void and return, and reuse them to convert temperatures.

A function groups code under a name so you can reuse it. It is declared with its return type, its name and its parameters with their types: double toFahrenheit(double celsius) takes degrees Celsius and `return` hands back the result.
A `void` function returns nothing: printLine(26) just prints a row of 26 dashes. The argument 26 is copied into the width parameter.
return ends the function the moment it runs. In describe, if the temperature is below 10 it returns cold and looks no further, which is why no else is needed.
Parameters can be of any type, including a std::vector. average checks with empty() that there is data before dividing. The functions are written before main, which uses them, because the compiler reads the file from top to bottom.
In main, a range-based for calls two functions for each day, and one function's result can go straight into another: describe(average(week)).
Code · main.cpp
#include <iostream>#include <string>#include <vector>// A function: return type, name, parameters and body.double toFahrenheit(double celsius) { return celsius * 9 / 5 + 32; }// void: it does something, but returns nothing.void printLine(int width) { for (int i = 0; i < width; i++) std::cout << '-'; std::cout << '\n';}// return ends the function as soon as it runs.std::string describe(double celsius) { if (celsius < 10) return "cold"; if (celsius < 25) return "mild"; return "hot";}double average(std::vector<double> values) { double sum = 0; for (double v : values) sum += v; return values.empty() ? 0 : sum / values.size();}int main() { std::vector<double> week = {8.5, 14.0, 22.5, 27.0, 31.5}; printLine(26); for (double c : week) std::cout << c << " C = " << toFahrenheit(c) << " F, " << describe(c) << '\n'; printLine(26); std::cout << "Average: " << average(week) << " C, " << describe(average(week)) << '\n'; return 0;}Output · c++ -std=c++17 main.cpp -o main && ./main
-------------------------- 8.5 C = 47.3 F, cold 14 C = 57.2 F, mild 22.5 C = 72.5 F, mild 27 C = 80.6 F, hot 31.5 C = 88.7 F, hot -------------------------- Average: 20.7 C, mild
Key points
- Return type, name and parameters:
double f(double x). returnhands back the value and ends the function.voidmeans it returns nothing.- A function must be declared before it is used.
- One function's result can be another's argument.
Exercise
Write double toCelsius(double fahrenheit) and int countHot(std::vector<double> temps), which counts the days above 25 degrees, and use them in main.