Great! Welcome to Day 3 of learning C++. Today, we will explore fundamental parameter passing, scope, and functions. Writing modular, reusable, clean code depends on these fundamental ideas.
C++ Day 3: Scope and Functions
1. What is a Function?
A task done by a block of code known as a function is Functions help to divide a big program into more manageable parts.
2. Function Syntax
return_type function_name(parameter1, parameter2, . . . ) {
// Code to run
value return; // if return_type is not void
{
✅ Example:
int add(int a, int b)
return a + b;
}
int main
std::cout << add(5, 3); // Output: 8
return 0.
}}
Three kinds of functions:
Void functions lack return value.
Return-type functions: Give back a value.
Parameterless functions: No input
Parameterized functions: Accept input
four. Definition versus Declarations of Function
Prototype declaration:
Tells the compiler a function exist: int multiple(int, int);
Definition:
int multiply(int x, int y) {
return x * y;
}
Scope in C++ five.
Scope is the area of a program wherein a variable is created and accessible.
Inside a function or block, local scope
Global scope: outside all activities
Inside the function only: functional scope
Example:
int globalVar = 10;
void show() {
int local Variable = 5;
std::cout << globalVar; // good
std::cout << localVar; // OK
}
int main() {
std::cout << globalVar; // OK
// std::cout << localVar; Error
return 0;
}
6. Pass by Value versus Pass by Reference
Pass by Value:
The function copies the variable.
void square(int x) {
x = x times x;
}
int main()
int num = 5;
square ( num );
std::cout << num; // Output: 5
}
Passing by Reference:
The function receives a reference, therefore the original may be changed.
void square(int &x)
x = x times x;
}}
int main() {
int num = 5;
square(num);
std::cout << num; // Output: 25
]
✅ Summary for Day 3:
You discovered how to define and declare functions.
C++ let you investigate several different scopes.
You discovered by reference and by value how data is transmitted to functions.
C++ Day 34: Layout Layouts (Part 2) We’ll cover: Constructer Layout Adjuster Layout Decorator Layout practise Task 🔹 1. developer form (creational) used to make compound objects measure away step ✅ employ case: you need to form associate in nursing aim (like amp pizza pie calculator house) with elective parameters example: cpp copy edit class calculator { train Methodor gpu ram; public: family developer { train Methodor gpu ram; public: developer setcpu(string c) { Methodor = c; take *this; } developer setgpu(string g) { gpu = g; take *this; } developer setram(string r) { run = r; take *this; } calculator Construct() { take Calculater(cpu gpu ram); } }; Calculater(string snow train m train r) : cpu(c) gp...
Comments
Post a Comment