A function is a block of code you name and write separately to handle one task. It makes code reusable, keeps your program easier to read, and makes bugs easier to track down. If you're doing something more than once, consider splitting it into a function.
cpp
#include <iostream>
using namespace std;
void showWelcome() {
cout << "Welcome to C++ lesson!" << endl;
}
int add(int a, int b) {
return a + b;
}
int main() {
showWelcome();
int total = add(5, 3);
cout << "Total: " << total;
return 0;
}showWelcome() just outputs something and doesn't need a return value, so it's declared void. add() takes two integers and returns an integer result, so its return type is int.
You should see
Welcome to C++ lesson! Total: 8Info
Name your functions so it's obvious what they do. doThing() versus calculateTotal() — the second one is a lot easier to understand when you come back to read it later.