0% found this document useful (0 votes)
16 views2 pages

Ag 3

coding

Uploaded by

Aadyasha Giri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views2 pages

Ag 3

coding

Uploaded by

Aadyasha Giri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

SCOPE OF A VARIABLE IN C++:

The scope of a variable in C++ refers to the region of the program where
the variable is accessible. It defines where in the code the variable can
be used or modified. There are mainly three scopes in C++:

1. LOCAL SCOPE: Variables declared inside a function or a block have


local scope. They are only accessible within that specific function or
block.
void myFunction() {
int localVar = 10; // localVar has local scope
}

2. GLOBAL SCOPE: Variables declared outside of any function or block have


global scope. They are accessible throughout the entire program.
int globalVar = 20; // globalVar has global scope

void anotherFunction() {
// globalVar can be accessed here
}

3. CLASS SCOPE: (Member Variables): Variables declared as class members


have class scope. They are accessible within the class and its member
functions.
class MyClass {
public:
int classVar; // classVar has class scope
};

APPLICATIONS OF SCOPE RESOLTION OPERATOR (::):

1. Accessing Global Variables from Local Scope:

int globalVar = 30;

int main() {
int globalVar = 5;
std::cout << ::globalVar; // Accessing the global variable using the
scope resolution operator
return 0;
}

2. Accessing Class Members:


class MyClass {
public:
int classVar = 15;
};

int main() {
MyClass obj;
std::cout << obj.classVar; // Accessing the class member using the
scope resolution operator
return 0;
}

3. Namespace Usage:
namespace MyNamespace {
int x = 42;
}

int main() {
std::cout << MyNamespace::x; // Accessing the variable in a
namespace using the scope resolution operator
return 0;
}

The scope resolution operator is important for distinguishing variables


with the same name in different scopes and for accessing global variables
or class members from within local scopes.

You might also like