C++ course menu
C++ Functions: Defining, Calling, Returning Values and Declarations
Learn C++ functions: defining and calling them, parameters and return values, void functions, function declarations (prototypes), splitting code into header and source files, and writing small, single-purpose functions.
On this page
A function is a named block of code that does one job. You write it once and call it whenever you need that job done. Functions make programs shorter, easier to test, and easier to understand, because each piece has a name that says what it does.
You have already used one function in every program: main.
Defining and calling a function#
#include <iostream>
void greet() {
std::cout << "Welcome to Laviyx Learn!\n";
}
int main() {
greet();
greet();
}Welcome to Laviyx Learn!
Welcome to Laviyx Learn!A function definition has:
- a return type (
voidmeans "returns nothing"); - a name (
greet); - a parameter list in parentheses (empty here);
- a body in braces.
Calling it means writing its name followed by parentheses: greet();.
Parameters: giving a function input#
Parameters are variables that receive the values passed in a call (the arguments):
#include <iostream>
#include <string>
void greet(const std::string& name, int visits) {
std::cout << "Hello, " << name << "! Visit number " << visits << ".\n";
}
int main() {
greet("Asha", 3);
greet("Ravi", 1);
}Hello, Asha! Visit number 3.
Hello, Ravi! Visit number 1.Arguments are matched to parameters by position, and each must have a compatible type. const std::string& is the usual way to pass a string without copying it; Parameters explains why.
Returning a value#
A function with a return type other than void sends a value back with return:
#include <iostream>
double rectangle_area(double width, double height) {
return width * height;
}
int main() {
double area = rectangle_area(4.5, 2);
std::cout << "Area: " << area << '\n';
std::cout << "Twice: " << 2 * rectangle_area(3, 3) << '\n';
}Area: 9
Twice: 18The call rectangle_area(4.5, 2) is an expression whose value is the returned result, so you can store it, print it, or use it in a calculation.
return also ends the function immediately. That lets you handle special cases first:
#include <iostream>
int safe_divide(int a, int b) {
if (b == 0) {
return 0; // early return for the special case
}
return a / b;
}
int main() {
std::cout << safe_divide(10, 3) << ' ' << safe_divide(5, 0) << '\n';
}3 0Every path through a non-void function must return a value. Reaching the end without one is undefined behaviour, and -Wall warns about it.
Returning a bool#
Functions that answer a yes/no question usually return bool and are named like a question:
#include <iostream>
bool is_even(int n) {
return n % 2 == 0;
}
int main() {
for (int i = 1; i <= 4; ++i) {
std::cout << i << (is_even(i) ? " even" : " odd") << '\n';
}
}1 odd
2 even
3 odd
4 evenDeclarations (prototypes)#
The compiler reads files from top to bottom, so a function must be declared before it is called. If you want main at the top, put a declaration (also called a prototype) first, and the full definition later:
#include <iostream>
int square(int n); // declaration: name, parameters, return type
int main() {
std::cout << square(7) << '\n';
}
int square(int n) { // definition: the body
return n * n;
}49A declaration ends with ; instead of a body.
Splitting code into files#
In real projects, declarations go in a header file (.h or .hpp) and definitions in a source file (.cpp):
#pragma once
double circle_area(double radius);#include "geometry.h"
double circle_area(double radius) {
return 3.141592653589793 * radius * radius;
}#include <iostream>
#include "geometry.h"
int main() {
std::cout << circle_area(2) << '\n';
}Compile all source files together:
g++ -std=c++20 -Wall main.cpp geometry.cpp -o app#pragma once (or the older #ifndef/#define include guards) stops a header from being included twice in the same file.
Writing good functions#
- One job per function. If you need "and" to describe it, consider splitting it.
- Name it with a verb for actions (
print_report,calculate_tax) or a question forboolresults (is_valid). - Keep it short. A function that fits on one screen is easier to read and test.
- Prefer returning results over printing them; the caller can then decide what to do with the value.
Common mistakes#
Practice#
Practice exercise
Write a function celsius_to_fahrenheit(double c) that returns c * 9 / 5 + 32, and a function describe(double c) that prints, for example, 30 C = 86 F. Call describe for 0, 37 and 100.
Show solution
#include <iostream>
double celsius_to_fahrenheit(double c) {
return c * 9 / 5 + 32;
}
void describe(double c) {
std::cout << c << " C = " << celsius_to_fahrenheit(c) << " F\n";
}
int main() {
describe(0);
describe(37);
describe(100);
}0 C = 32 F
37 C = 98.6 F
100 C = 212 FPractice exercise
Write bool is_prime(int n) and use it to print all prime numbers from 1 to 30 on one line.
Show solution
#include <iostream>
bool is_prime(int n) {
if (n < 2) return false;
for (int d = 2; d * d <= n; ++d) {
if (n % d == 0) return false;
}
return true;
}
int main() {
for (int i = 1; i <= 30; ++i) {
if (is_prime(i)) std::cout << i << ' ';
}
std::cout << '\n';
}2 3 5 7 11 13 17 19 23 29Key takeaway#
Finished this lesson?