Scope and Lifetime of Variables in Cpp
Scope and Lifetime of Variables
A. Local variables within functions
Local variables are declared inside a function and are only accessible within that function.
They are created when the function is called and destroyed when it finishes executing.
Local variables are useful for storing temporary data or intermediate calculations within a function.
B. Global variables and their accessibility
Global variables are declared outside of any function and can be accessed by all functions in the program.
They have a global scope and can be used across multiple functions.
Global variables are initialized before the program starts and remain in memory until the program terminates.
Excessive use of global variables can make code harder to understand and maintain, so they should be used judiciously.
C. Scope and lifetime of variables
Scope refers to the region of code where a variable is visible and can be accessed.
Lifetime refers to the time during which a variable exists and holds its value.
The scope of a local variable is limited to the block in which it is declared (e.g., within a function or a loop).
The lifetime of a local variable begins when the block is entered and ends when the block is exited.
Global variables have a scope that extends throughout the program, and their lifetime is from program start to program end.
D. Example illustrating variable scope and lifetime
Example: Global variable scope and lifetime:
int globalVar = 10; // Global variable
void modifyGlobalVar() {
globalVar += 5;
}
void displayGlobalVar() {
cout << "Global variable: "<< globalVar << endl;
}
int main() {
displayGlobalVar(); // Output: Global variable: 10
modifyGlobalVar();
displayGlobalVar(); // Output: Global variable: 15
return 0;
}
Passing Arrays to Functions
A. Syntax for passing arrays as function arguments
Arrays can be passed to functions by specifying the array name as the argument.
When passing arrays, it is common also to pass the array size as an additional argument.
B. Modifying arrays within functions
By default, arrays are passed by reference, allowing modifications made within the function to affect the original array.
Modifying array elements within a function can be done directly using the array indices.
C. Examples showcasing passing arrays to functions
Example 1: Calculating the sum of array elements:
void calculateSum(int arr[], int size) {
int sum = 0;
for (int i = 0; i < size; i++) {
sum += arr[i];
cout << "Sum: " << sum << endl;
}
int main() {
int numbers[] = {1, 2, 3, 4, 5);
int size = sizeof(numbers) / sizeof(numbers[0]);
calculateSum(numbers, size);
return 0;
}
Example 2: Modifying array elements within a function:
void doubleElements(int arr[], int size) {
for (int i = 0; i < size; i++) {
arr[i] *= 2;
}
}
int main() {
int numbers[]= {1, 2, 3, 4, 5};
int size= sizeof(numbers) / sizeof(numbers[0]);
doubleElements (numbers, size);
for (int i = 0; i < size; i++) {
cout << numbers[i] << " ";
}
cout << endl;
return 0;
}
Example 3: Finding the maximum element in an array:
int findMax(int arr[], int size) {
int max = arr[0];
for (int i = 1; i < size; i++) {
if (arr[i]> max) {
max= arr[i];
}
}
return max;
}
int main() {
int numbers[] = {5, 3, 8, 2, 1};
int size = sizeof(numbers) / sizeof(numbers[0]);
int maxElement = findMax (numbers, size);
cout << "Maximum element: " << maxElement << endl;
return 0;
}
Function Templates
A. Introduction to function templates
Function templates provide a way to create generic functions that can work with different data types.
Templates allow for code reuse and provide flexibility in handling various data types without duplicating code.
B. Syntax and usage of function templates
Function templates are defined using the keyword "template" followed by the template parameter(s) in angle brackets.
Template parameters represent the generic types or values that can be used within the function.
The template parameters are then used to declare the function parameters, return type, and within the function body.
When calling a function template, the actual data types or values are specified, and the compiler generates the appropriate code.
C. Benefits and flexibility of function templates
Code reuse: Function templates allow you to write a single function that can work with multiple data types.
Type safety: Function templates ensure type safety by allowing the compiler to perform type-checking during compilation.
Flexibility: Templates provide flexibility to handle different data types without the need for redundant code.
Generic algorithms: Function templates are commonly used in generic algorithms, such as sorting or searching, where the underlying data type can vary.
D. Examples demonstrating function templates
Example 1: Adding two numbers using a function template:
template<typename T>
Tadd(T nuni, T num2) {
return num1 + num2;
}
int main() {
int result1= add (5, 7); // inferred type: int
double result2 = add(3.14, 2.71); // inferred type: double
cout << "Result 1: " << result1 << endl;
cout << "Result 2: " << result2 << endl;
return 0;
}
Example 2: Finding the maximum of two values using a function template:
template<typename T>
T maximum (T value1, T value2) {
return (value1 > value2) ? value1: value2;
}
int main() {
int maxInt = maximum (5, 7); // inferred type: int
double maxDouble = maximum (3.14, 2.71); // inferred type: double
cout << "Max Integer: " << maxInt << endl;
cout << "Max Double: " << maxDouble << endl;
return 0;
}
Example 3: Generic swapping using a function template:
template<typename T>
void swapValues(T& value1, T& value2) (
T temp = value1;
value1 = value2;
value2 = temp;
}
int main() {
int a = 5, b = 7;
swapValues(a, b); // inferred type: int
cout<<"Swapped values: " << a << ", "<< b << endl;
double x 3.14, y = 2.71;
swapValues(x, y); // inferred type: double
cout << "Swapped values: " << x << ", " << y << endl;
return 0;
}