0% found this document useful (0 votes)
10 views

Module 3. Lesson Proper

The document explains variable scope in C++, detailing local and global scopes, their visibility, and lifetime. It also covers the use of multiple variables, including declaring them, variable shadowing, and using them in expressions, loops, and functions. Additionally, it discusses variables, literals, and constants, highlighting their definitions, types, and differences between const variables and #define constants.

Uploaded by

talidong885
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Module 3. Lesson Proper

The document explains variable scope in C++, detailing local and global scopes, their visibility, and lifetime. It also covers the use of multiple variables, including declaring them, variable shadowing, and using them in expressions, loops, and functions. Additionally, it discusses variables, literals, and constants, highlighting their definitions, types, and differences between const variables and #define constants.

Uploaded by

talidong885
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

C++ VARIABLE SCOPE AND MULTIPLE VARIABLES

Variable scope refers to the region or context within a program where a variable is
accessible or can be used. Understanding variable scope is crucial because it determines the
visibility and lifetime of a variable within a program.

Types of Variable Scope

1. Local Scope

Definition: A variable declared inside a function or a block (such as within {}) is said
to have local scope.
Visibility: The variable is only accessible within the block or function where it is
declared.
Lifetime: The variable exists only during the execution of the block or function. Once
the block or function exits, the variable is destroyed.

Example:

#include <iostream>
using namespace std;

void exampleFunction() {
int localVar = 10; // localVar is local to exampleFunction
cout << "Inside function: " << localVar << endl; // Accessible here
} // localVar is destroyed here

int main() {
exampleFunction();
// cout << localVar; // Error: localVar is not accessible here
return 0;
}

Note: Local Scope: Limited to the function/block where declared.

2. Global Scope

Definition: A variable declared outside all functions and blocks is considered to have
global scope.
Visibility: The variable is accessible from any part of the program after its
declaration.
Lifetime: The variable exists throughout the entire execution of the program and is
destroyed when the program terminates.

Example:

#include <iostream>
using namespace std;

int globalVar = 20; // globalVar is global


void exampleFunction() {
cout << "Inside function: " << globalVar << endl; // Accessible here
}

int main() {
cout << "Inside main: " << globalVar << endl; // Accessible here
exampleFunction();
return 0;
}

Note: Global Scope: Accessible anywhere in the program after declaration.

Multiple Variables

In C++, you can work with multiple variables in various ways, depending on how and
where they are declared and used. Here's a detailed overview:

1. Declaring Multiple Variables in a Single Statement


C++ allows you to declare multiple variables of the same type in a single statement,
separated by commas.

Example:

int a, b, c; // Declares three integer variables a, b, and c


float x = 1.5, y = 2.5, z = 3.5; // Declares and initializes three float variables

Note: Declaration: Multiple variables of the same type can be declared in a single statement.

2. Multiple Variables with Different Scopes


You can declare variables with the same name in different scopes (e.g., global, local,
block), but they will refer to different entities.

Example:

#include <iostream>
using namespace std;

int var = 10; // Global variable

int main() {
int var = 20; // Local variable in main function
{
int var = 30; // Block-scoped variable
cout << "Block scope var: " << var << endl; // Outputs 30
}
cout << "Local scope var: " << var << endl; // Outputs 20
cout << "Global scope var: " << ::var << endl; // Outputs 10 using scope resolution operator
return 0;
}

Note: Scope: Multiple variables can exist in different scopes with the same name (global, local,
block), leading to shadowing.
3. Variable Shadowing
When a local variable has the same name as a global variable, the local variable
"shadows" the global variable within its scope. The global variable can still be accessed
using the scope resolution operator ::.

Example:

#include <iostream>
using namespace std;

int x = 5; // Global variable

void exampleFunction() {
int x = 10; // Local variable shadows global x
cout << "Local x: " << x << endl; // Outputs 10
cout << "Global x: " << ::x << endl; // Outputs 5 using scope resolution operator
}

int main() {
exampleFunction();
return 0;
}

4. Using Multiple Variables in Expressions


You can perform operations on multiple variables within expressions, and C++
handles the operations according to the types and precedence rules.

Example:

#include <iostream>
using namespace std;

int main() {
int a = 10, b = 20, c = 30;
int sum = a + b + c; // Sum of multiple variables
int product = a * b * c; // Product of multiple variables

cout << "Sum: " << sum << endl; // Outputs 60


cout << "Product: " << product << endl; // Outputs 6000
return 0;
}
Note: Expressions: Multiple variables can be used in arithmetic and logical expressions.

5. Multiple Variables in Loops


C++ allows you to declare and use multiple variables within loops. You can also
manage the scope of loop variables to ensure they don't interfere with other parts f the
program.
Example:

#include <iostream>
using namespace std;

int main() {
for (int i = 0, j = 10; i < 5; i++, j--) {
cout << "i: " << i << ", j: " << j << endl;
}
// i and j are not accessible here because their scope is limited to the for loop
return 0;
}

Note: Loops: C++ allows multiple variables in loop control structures.

6. Passing Multiple Variables to Functions


You can pass multiple variables as arguments to a function, and C++ allows you to
work with them inside the function.

Example:

#include <iostream>
using namespace std;

void printSumAndProduct(int x, int y) {


int sum = x + y;
int product = x * y;
cout << "Sum: " << sum << ", Product: " << product << endl;
}

int main() {
int a = 5, b = 10;
printSumAndProduct(a, b); // Passes two variables to the function
return 0;
}

Note: Functions: Functions can accept multiple variables as parameters.

7. Using Multiple Variables with Arrays


Arrays allow you to manage multiple variables of the same type under a single name.

Example:

#include <iostream>
using namespace std;

int main() {
int arr[3] = {1, 2, 3}; // Array of three integers
for (int i = 0; i < 3; i++) {
cout << "arr[" << i << "]: " << arr[i] << endl;
}
return 0;
}

Note: Arrays: Arrays manage multiple variables of the same type efficiently.

Variables, literals, and constants are fundamental concepts that allow you to store, manage,
and manipulate data within a program.

1. Variables

Definition
A variable in C++ is a named storage location in memory that can hold a value.
The value of a variable can be changed during the execution of a program.

Declaration: Declares a variable by specifying its type and name.


Initialization: Assigns an initial value to the variable.

Example:

#include <iostream>
using namespace std;

int main() {
int age; // Declaration of an integer variable
age = 25; // Initialization of the variable
int year = 2024; // Declaration and initialization in one statement
cout << "Age: " << age << endl;
cout << "Year: " << year << endl;
return 0;
}

Variable Types

Variables can be of various types, such as:

int: Integer numbers.


float: Floating-point numbers.
double: Double-precision floating-point numbers.
char: Single characters.
bool: Boolean values (true or false).

Example:

#include <iostream>
using namespace std;

int main() {
int a = 10; // Integer variable
float b = 5.5f; // Floating-point variable
double c = 3.14; // Double variable
char d = 'A'; // Character variable
bool e = true; // Boolean variable
return 0;
}

2. Literals

Definition
A literal is a constant value that is directly written into the code. It represents
fixed values that do not change during the execution of the program.

Types of Literals

Integer Literals: Represents whole numbers.


Floating-point Literals: Represents decimal numbers.
Character Literals: Represents single characters, enclosed in single quotes.
String Literals: Represents sequences of characters, enclosed in double quotes.
Boolean Literals: Represents true or false.

Example:

#include <iostream>
using namespace std;

int main() {
int a = 10; // Integer literal
float b = 5.5f; // Floating-point literal
char c = 'A'; // Character literal
const char* str = "Hello"; // String literal
bool d = true; // Boolean literal
return 0;
}

3. Constants
Definition
A constant in C++ is a variable whose value cannot be changed once it has been
initialized. Constants are used to protect data from being modified accidentally.

Declaring Constants

const Keyword: Used to declare a constant variable.


#define Directive: Used to define constant values using preprocessor directives.

Example with const:

#include <iostream>
using namespace std;

int main() {
const int PI = 3.14159; // Declaring a constant using const
// PI = 3.14; // Error: PI is a constant and cannot be modified
cout << "PI: " << PI << endl;
return 0;
}

Example with #define:

#include <iostream>
#define PI 3.14159 // Declaring a constant using #define
using namespace std;

int main() {
cout << "PI: " << PI << endl;
// PI = 3.14; // Error: PI is a constant and cannot be modified
return 0;
}

Differences Between const and #define:

 const Variables:

Type-safe: Enforces type checking.


Scoped: Limited to the scope where it is defined.

 #define Constants:

No type checking: It is simply a text replacement before compilation.


Global scope: Available throughout the entire file.

You might also like