
A function is a command you invent yourself: write it once, call it as often as you like. It breaks a long program into small, understandable pieces.
ON THIS PAGE
SHOW EXAMPLE IN
//THE EXAMPLE
main.cpp
#include <iostream>
using namespace std;
int square(int x) {
return x * x;
}
void greet(string name) {
cout << "Hello, " << name << "!" << endl;
}
int main() {
cout << square(5) << endl; // 25
cout << square(9) << endl; // 81
greet("Saraa");
return 0;
}> what you see
25 81 Hello, Saraa!
//LINE BY LINE
Watch it run
main runs from the top down and reaches its first call.
Why functions exist
- Use one piece of work in many places without repeating it.
- Break a long program into small, named pieces.
- Fix a bug in one place instead of five.
The parts of a function
int square(int x) {
// ↑ ↑ ↑
// | | └── параметр: юу авах вэ
// | └───────── нэр
// └─────────────── буцаах төрөл
return x * x;
}A function that returns nothing has the return type void.
void greet(string name) {
cout << "Hello, " << name << endl;
// return хэрэггүй
}A function must be declared before it is used, so write your functions above main.