C++ Functions
A function groups code under one name for a single job. Writing the name in a statement runs the code inside the function.
A function that prints a line
The greet function holds one print statement. Main calls greet once.
#include <iostream>
void greet() {
std::cout << "Hello" << std::endl;
}
int main() {
greet();
return 0;
}Calling a function twice
Main calls greet two times. The print statement runs each time.
#include <iostream>
void greet() {
std::cout << "Hello" << std::endl;
}
int main() {
greet();
greet();
return 0;
}One function, one job
This function has one job only. It prints a separator line between two parts.
#include <iostream>
void printSeparator() {
std::cout << "----------" << std::endl;
}
int main() {
std::cout << "Report" << std::endl;
printSeparator();
std::cout << "Details" << std::endl;
return 0;
}Example
#include <iostream>
void printHeader() {
std::cout << "My Day" << std::endl;
}
void printFooter() {
std::cout << "Done" << std::endl;
}
int main() {
printHeader();
std::cout << "Study" << std::endl;
std::cout << "Practice" << std::endl;
printFooter();
return 0;
}Key points
- A function definition starts with void, then a name, then parentheses.
- Curly braces hold the statements of a function.
- A call writes the function name with parentheses and a semicolon.
- A definition sits above main so main can call the function.
- One function can be called many times in a program.
- Each function does one small job.
In this example, printHeader prints the title line My Day. Main then prints two activity lines. printFooter prints the closing line Done.
Note
main is also a function, and running starts there.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does a call to a function do?