Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we delete name of a variable in C++?

Tags:

c++

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.

like image 376
Milad R Avatar asked Dec 07 '22 16:12

Milad R


2 Answers

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
        ...
    }
}
like image 154
Sufian Latif Avatar answered Dec 15 '22 00:12

Sufian Latif


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;
        ...
    }
}
like image 24
Oliver Charlesworth Avatar answered Dec 15 '22 00:12

Oliver Charlesworth