Wednesday, May 27, 2009

The least you need to know about scopes in C++

A scope is basically a location where code is bound to. The two main scopes in C++ are the global scope and function scope (we'll be getting more into functions soon ;)) Consider the following program:

//This is global scope
#include

typedef unsigned short int USHORT;

USHORT myglobalvariable = 15;

void afunction();

int main(){
//This is main scope
USHORT mymainvariable = 8;

myglobalvariable = 7;

afunction();

return 0;

}

void afunction(){
//This is afuntion scope
USHORT myafunctionvariable = 9;

myglobalvariable = 6;
}


The variable declared globally can be accessed and/or modified anywhere in the program. The variable declared in main() can only be accessed and/or modified in main(). The variable declared in afunction() can only be accessed and/or modified in afunction().

No comments:

Post a Comment