📅 Date: Jan 7, 2026
🔥 Topic: Functions (Part 2): Parameters & Return Types
🔄 Sending & Receiving Data
Yesterday's function was static. Today, I learned how to make functions dynamic by passing data into them (Parameters) and getting results back (Return Values).
1️⃣ Parameters (Inputs)
These are variables inside the parentheses ( ) that accept values when the function is called.
2️⃣ Return Statement (Output)
Instead of printing the result, a function can throw the result back to main() using the return keyword.
💻 Day 7 Code: The Adder
Here is a function that takes two integers, adds them, and returns the result.
#include <iostream>
using namespace std;
// Function that takes input and returns output
int addNumbers(int a, int b) {
int sum = a + b;
return sum; // Throwing value back
}
int main() {
int num1 = 10, num2 = 20;
// Catching the returned value
int result = addNumbers(num1, num2);
cout << "The sum is: " << result << endl;
// Direct usage
cout << "Direct sum: " << addNumbers(50, 50) << endl;
return 0;
}
⚠️ Scope Alert!
I learned an important concept: Local Scope. Variables created inside a function (like sum above) cannot be accessed inside main(). They die when the function ends.
💠Thoughts
Functions are powerful. Next up, I need to understand Pass by Value vs Pass by Reference because I heard that changes variables differently.
No comments:
Post a Comment