Loading lessons...
Introduction to Functions
Introduction to Functions
A function is a named block of code that runs when you call it. Instead of typing the same statements over and over, you write them once inside a function and reuse them wherever you need.
Why functions?
- Reuse: run the same code from many places without rewriting it.
- Organization: a program becomes a collection of small, understandable pieces instead of one giant wall of code.
- Readability: a function named
showMenutells you instantly what that chunk does.
Basic syntax
A function has a return type, a name, parentheses, and a body in braces:
void myFunction() {
cout << "I just got executed!";
}
voidmeans the function returns nothing (we'll cover return types soon).- The name
myFunctionis how we refer to it. ()can hold parameters; for now they are empty.- The body is the code between the curly braces
{ }.
Calling a function
The function doesn't run on its own. You have to call it, by name, with parentheses, ending in a semicolon:
int main() {
myFunction(); // "I just got executed!"
myFunction(); // each call runs the whole body again
return 0;
}
Define once, call many times
A function's body only appears once in your code, but you can call it as many times as you like. Every call jumps to the body, runs every statement in it, and then comes back.
TL;DR
- A function is a named, reusable block of code.
- Functions give you reuse, organization, and readability.
- Syntax:
void myFunction() { }- return type, name, parentheses, braces. - To run it, call it:
myFunction();. - Each call executes the whole body again.