C++ Functions
A function is a reusable named block of code with a return type, a name, and a parameter list, e.g. `int add(int a, int b) { return a + b; }`. Functions must be declared (or defined) before they're called, or you need a forward declaration.
Breaking a program into functions improves readability, avoids repetition, and makes testing individual pieces easier.
Defining and calling
A function definition specifies its return type, name, and parameters. Calling it with matching arguments executes the body and returns a value via `return`.
void functions
A function that returns nothing uses `void` as its return type and simply ends without a `return value;` statement (a bare `return;` is optional).
int add(int a, int b) {
return a + b;
}
int main() {
std::cout << add(2, 3);
}5add() takes two ints and returns their sum.
void greet() {
std::cout << "Hi!";
}
int main() { greet(); }Hi!void functions don't return a value.
Key points
- Functions have a return type, name, and parameters.
- void means the function returns nothing.
- Functions must be declared before use (or forward-declared).
- Breaking code into functions improves reuse and clarity.
