krylov
krylov

Reputation: 79

Variables with the same name when using for loop in C++

Consider the following code snippet:

unsigned int i;
double* u = new double [10];

for (i=0; i<10; i++)
{
    double u = 5.0;
    // Other code
}

delete[] u;

Is it okay to use the variable name u twice? Or is this frowned upon? Will the code fail to compile using certain compilers?

EDIT: Is this better? Or is it still confusing for future maintainers of the code?

unsigned int i;
double* u = new double [10];
// Do stuff with u
delete[] u;

for (i=0; i<10; i++)
{
    double u = 5.0;
    // Other code
}

Upvotes: 2

Views: 187

Answers (2)

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

The code

double u = 5.0;

inside of the loop will shadow the definition

double* u = new double [10];

made prior to it.
All of your code inside the loop just sees double u. It's meant to compile fine, and besides introducing confusion for future maintainers of the code, there's nothing wrong from a syntactical point of view.


Note:
If you aren't using double* u inside of the loop, there's no point defining this variable before it. As a rule of thumb:

Local variable definitions should appear nearest before their first point of usage.


As for your edited question:
Yes this will be clearer, in the sense that one could see the intend double* u; shouldn't be used after the delete[] u;. Though it's neither safe, and still confusing, if one's not spotting the shadowing definition of double u; inside of the loop immediately.

The IMHO overall better solution, to not confuse anyone, would be to factor out the code in the loop, or the code dealing with the double* u into a separate function, or even simply use a different variable name.

Upvotes: 4

Logicrat
Logicrat

Reputation: 4468

That will work with most compilers. However, it is generally not a good practice as it can lead to confusion on the part of the programmer, particularly if the program becomes large.

Upvotes: 1

Related Questions