variable reuse

R

Robin

Suppose I define a variable int a; and I want to be able to use the
same name a for a string variable or an int variable or any sort of
variable later on...how can I undefine it so I can do this?

Thanks in advance,
-Robin
 
V

Victor Bazarov

Suppose I define a variable int a; and I want to be able to use the
same name a for a string variable or an int variable or any sort of
variable later on...how can I undefine it so I can do this?

You cannot undefine a variable. The name (and the definition) persists
to the end of the scope, which means you need to define your variables
each in its own scope, if you would like to reuse the name.

That said, two thoughts come to mind. First, don't name your variables
'a'. It's non-informative. It's better if the variable name is
self-documenting. Second, if you think you could reuse the name, it
sounds that either the name is too generic, or your algorithm should
probably be split into two portions and each wrapped in a function.

What is your intention in reusing the name? Obfuscation? Hope not.
Are you trying to optimize something? If yes, what? Also, it is quite
useful to post your code (even with parts removed) to illustrate your
points.

V
 
J

John H.

Victor said:
The name (and the definition) persists
to the end of the scope, which means you need to define your variables
each in its own scope, if you would like to reuse the name.

Example:

int main()
{
int a = 97;

{ // Start a new block to begin a new scope
char a = 'a'; // now we can declare another "a" variable
}

{
char a[] = "a";
}

// The following would produce a compilation
// error because it would try to declare two a
// variables in the same scope
// double a = 97.0;
}
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top