Notifications
Clear all
Topic starter 01/08/2025 11:29 pm
In C++, functions are like reusable mini-programs that help you organize your code into logical chunks. They make your programs cleaner, easier to understand, and more efficient 🧠🔧
🧱 What Is a Function?
A function is a named block of code that performs a specific task. You define it once and call it whenever you need it.
void greet() {
std::cout << "Hello there!";
}
void
means the function doesn’t return a value.greet
is the function name.- The code inside
{}
runs when you callgreet();
🔁 Calling a Function
int main() {
greet(); // This calls the function
return 0;
}
Functions don’t run until they’re called—like pressing “play” on a playlist.
🧪 Functions with Parameters
You can pass data into functions:
void greet(std::string name) {
std::cout << "Hello, " << name << "!";
}
Call it like: greet("Alice");
🔙 Returning Values
Functions can return results:
int add(int a, int b) {
return a + b;
}
Use it like:
int result = add(3, 5);
std::cout << result; // Output: 8
🧠 Function Declaration vs Definition
You can declare a function before main()
and define it later:
// Declaration
int square(int);
// main function
int main() {
std::cout << square(4);
return 0;
}
// Definition
int square(int x) {
return x * x;
}
This helps organize your code better.
⚙️ Advanced Features
- Default arguments:
int add(int a, int b = 10);
- Function overloading: Multiple functions with the same name but different parameters.
- Inline functions: Hint to the compiler to insert code directly for speed.