Accessing global variable in a local block

S

shilpa

Hi,
I just wanted to know whether we can access global variable within a
local block , where both variables are having same name.

For ex:

int temp=5 ;

{
int temp=10;
cout<<temp++;
}

Is it possible to access the global temp variable in the local block.
If yes, please let me know.
 
P

peter koch

shilpa skrev:
Hi,
I just wanted to know whether we can access global variable within a
local block , where both variables are having same name.

For ex:

int temp=5 ;

{
int temp=10;
cout<<temp++;
}

Is it possible to access the global temp variable in the local block.
If yes, please let me know.

It is - but don't obfuscate your code. Instead, rename one of your
variables. The global temp can be accessed as ::temp.

/Peter
 
P

Phlip

peter said:
It is - but don't obfuscate your code. Instead, rename one of your
variables. The global temp can be accessed as ::temp.

And don't call it temp.

;-)
 
G

Gianni Mariani

shilpa said:
Hi,
I just wanted to know whether we can access global variable within a
local block , where both variables are having same name.

For ex:

int temp=5 ;

{
int temp=10;
cout<<temp++;
}

Is it possible to access the global temp variable in the local block.
If yes, please let me know.

{
int & outer_temp = temp;
int temp=10;
cout<<outer_temp++;
}
 
B

BobR

shilpa wrote in message
Hi,
I just wanted to know whether we can access global variable within a
local block , where both variables are having same name.
For ex:

int temp=5 ;
{
int temp=10;
cout<<temp++;
}

Is it possible to access the global temp variable in the local block.
If yes, please let me know.

I still had this example/test laying around, try it.

#include <iostream>
#include <ostream>

int xyz(12345);

int main(){
std::cout<<" ------- "<<std::endl;
int abc(0), bla(0), blabla(5);
int xyz(5);
{ // scope
int xyz(22);
std::cout<<"xyz="<<xyz<<std::endl;
} // scope end
{ // scope
double xyz(3.14);
std::cout<<"xyz="<<xyz<<std::endl;
} // scope end
std::cout<<"abc="<<abc<<" bla="<<bla
<<" xyz="<<xyz<<std::endl;
for( int bla(0); bla < blabla; ++bla){
++abc;
std::cout << " abc=" << abc << " bla=" << bla;
static int xyz(25);
std::cout <<" xyz="<<xyz++<<" ::xyz="
<<( ::xyz++ )<<std::endl; // note global access
} // for(bla)
std::cout<<"abc="<<abc<<" bla="<<bla
<<" xyz="<<xyz<<std::endl;
return 0;
} // main()

Just because you can, should you? Using the same name for different things
can lead to confusion.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,024
Latest member
ARDU_PROgrammER

Latest Threads

Top