VC++ tutorial

Visual C++ Examples

How To Add Menu In VC++

Identifier and Scope in VC++
Previous Home Next

Every identifire has a scope that is determined by where it is declared. Identifire Socpe in a program is the regions of the program within which the identifire can be used. if a variable is in scope at a certain point in a program, it is visible and can be used in most circumstances. if it is "out of socpe," it is not visible, and your program will not be capable of using that variable.

The name from the most local scope is used. If the name is not defined in any enclosing scope, then the compiler will report an error.

Types of Scops:

File Scope: A name has file scope if its declaration appears outside of the blocks and classes.A name with file scope is visible from the point where it is declared to the end of the source file. The name is also made accessible for the initialization of global variables.

Note: File scope is available in C++ for backward compatibility with C, but we prefer to use namespaces or static class members instead.

#include <iostream>
using namespace std;
const double pi = 3.141;
double circleArea(double);
int main()
{
	double radius;
	cout <<"Enter a radius:";
	cin >> radius;
	double area = circleArea(radius);
	return 0;
}
double circleArea(double r)
{
	return pi*r*r
}

Function Scope: Labels in C/C++ have their own scope. They are accessible before and after their declaration, for the whole function. The only type of identifier with function scope is a label name. A label is implicitly declared by its appearance in the program text and is visible throughout the function that declares it.

Class Scope:An identifier that is declared inside a class definition has class scope. Class scope is anywhere in the class definition or in the bodies of member functions. All identifiers used in a class, union, or structure are tightly associated with the class and have class scope. An identifier with class scope can be used anywhere within the class, union, or structure.

int x = 25;
void fn1()
{
	cout<<"Global x is "<< x << endl;
}
void fn2 ()
{
	cout<<"Global x is "<< x << endl;
	for (int x = 0; x < 10; x++)
	{
		cout << "Inner x is " << x << endl;
		cout << "Global x is " << ::x << endl;
	}
	fn3(x);
	cout << x << endl;
}
void fn3(int x)
{
	x = -5;
	cout << "Parameter x is" << x << endl;
	cout << "Global x is" << ::x << endl;
}
Previous Home Next

Tolal:0 Click:

Show All Comments

Did not find what you were looking for leave your name and message. We will revert within 24 hours
Name:
eMail:
Comment / Feedback: