Question


I was doing an exercise in c++ program and i am posting here a part of that program which is giving me problem.

int max=100;
main()
{ int max=50;
 {
  int max=25;
  printf("%d",max);
  printf("%d",::max);
  //output will be 25 and 100
 // I wanted to use value "50" of max in this block i.e. the max variable of above block which is local to main
 // and I can't figure out how to do this.
 }
}

I know the :: operator does overwrites the priority of local with Global for the statement it is used but i want to do it for one block level up. Please Help me on this. I saw some references in book and on internet too, Actually i did reverse(first on internet and then in books) but i wasn't able to figure it out. Please help me on this.

My original piece of code is:

int max=100;
void main()
 {
   int max=50;
   char str[50];
   gets(str);
   if(strlen(str)>5)
    {
     int max=25;
     cout<<"Max here is"<<max<<endl;
     cout<<"Max above was"<</*max value of above block*/;
     cout<<"Max Global"<<::max;
    }
 }
Était-ce utile?

La solution

This is not possible. Inner local scopes completely shadow outer nesting scope names.

The best you can do is to make an alias before you shadow the outer name:

int max = 100;

int main() {
  int max = 50;
  {
    int &m_max = max; // make reference alias first!
    int max = 25;

    printf("%d %d %d\n", max, m_max, ::max); // have to use alias name :(
  }
}

Autres conseils

You cannot do the second declaration of variable max visible in the inner block because the variable with the same name in the inner block hides it. You can use qualified names only with variables declared in namespaces or class scopes. In your example you are using qualified name ::max that to access the variable declared in the global namespace.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top