📅 Date: Jan 6, 2026
🔥 Topic: Functions (Part 1): Definition & Syntax
🧩 Why Functions?
Until now, I was writing everything inside main(). It was getting messy.
Functions allow us to break our code into smaller, reusable blocks.
Think of a function as a "Mini-Program" inside your program. You write it once, and you can call it a thousand times.
🏗️ The Anatomy of a Function
A function has 3 main parts:
- Return Type: What does it give back? (
int,void, etc.) - Function Name: What do we call it? (e.g.,
printMenu) - Body: The code inside
{ }.
// Syntax
returnType functionName() {
// Code to be executed
}
💻 Day 6 Code: My First Function
I created a simple function that prints a welcome message. I realized that the function must be defined before main (or declared) to work.
#include <iostream>
using namespace std;
// Defining the Function
void sayHello() {
cout << "-----------------------" << endl;
cout << "Hello from a Function!" << endl;
cout << "-----------------------" << endl;
}
int main() {
cout << "Starting Main..." << endl;
// Calling the Function
sayHello();
sayHello(); // Reusability!
cout << "Ending Main..." << endl;
return 0;
}
💭 Thoughts
The keyword void means the function returns nothing. It just does its job and finishes. This makes the main() function look so much cleaner!
No comments:
Post a Comment