Question

Normally using the same identifier like name of a variable for something like another variable within the same scope generates error by compiler, Is there any technique to actually indicate to compiler that in this scope up to this specific point this name has its own purpose and is used to refer to this variable but after this point the same name is going to refer to something else like another variable with another purpose?

Was it helpful?

Solution

If you mean variables, no, there's not. When you create a variable, it's tied to a specific type and a specific location. Having said that, there's nothing stopping you from re-using the same variable for two different things:

float f = 3.141592653589;
// do something with f while it's PI
f = 2.718281828459;
// now do something with f while it's E.

You can use a pointer so that it can be changed to point to a different variable but that's not what you're asking, I suspect. In any case, unless you use a void pointer and cast it, it's still tied to a specific type:

float pi = 3.141592653589;
float e  = 2.718281828459;
float *f = π
// do something with *f while it's PI
f = &e;
// now do something with *f while it's E.

If what you're proposing is something like:

float f = 3.141592653589;
// do something with f while it's PI
forget f;
std::string f = "hello";
// do something with f while it's "hello"
forget f;

I'm not sure I see the point. I think you could do that by putting the definitions within a new scope (i.e., braces):

{
    float f = 3.141592653589;
    // do something with f while it's PI
}
{
    std::string f = "hello";
    // do something with f while it's "hello"
}

but it's not as if we have a world-wide shortage of variable names. And, if you're naming your variables well, it's pretty unlikely that a string and a float would even have the same name (double and float maybe but it's still an dubious function to add to the language).

OTHER TIPS

Well, you can use blocks within the function, each of which creates its own scope.

void func(void)
{
   int a;
   {
      int b;
      // here a can be used and b is an int
   }
   {
      double b;
      // here a can still be used, but int b went out of scope
      // b is now a double and has no relationship to int b in the other block
   }
}

Good fun when people ask about the extremely obscure corner cases of the language. One suspects a homework question (the one who posed the question would almost have to know "the" answer). But anyways, ...

#include <iostream>

struct ouch { int x; };
void ouch( ouch ) { std::cout << "ouch!" << std::endl; }

int main()
{
    struct ouch ah = {};
    ouch( ah );
}

Cheers & hth.,

void fn()
{
    int a = 1;
#define a b
    int a = 2;
}

but... a bit pointless to even try this though, right?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top