I want to know if it is possible that for example I defined int temp
then later, I define temp
as a float
.
I mean I want to use the name "temp" more than once in a .cpp
file. Is this possible? If it's possible, how?
edit: I meant in the same scope.
No, you can't declare two variables with the same name in the same scope. Their scopes must be different.
Like this:
int temp; // this is global
struct A
{
int temp; // this is member variable, must be accessed through '.' operator
};
int f1()
{
int temp; //local temp, though the global one may by accessed as ::temp
...
}
int f2()
{
int temp; //local
// a new scope starts here
{
int temp; //local, hides the outer temp
...
}
// another new scope, no variable of the previous block is visible here
{
int temp; // another local, hides the outer temp
...
}
}
There is no concept of deleting the name of a variable in C++. However, the lifetime and visibility of automatic variables is limited to the scope that they're declared in. So you could do something like the following:
void foo()
{
{
int temp;
...
}
{
float temp;
...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With