How bad is redefining/shadowing a local variable?

I noticed there were a lot of errors where a local variable was redefined inside a function for example.

You are not demonstrating redefining here. You show an example of variable shadowing.

Variable shadowing is not an error syntactically. It is valid and well defined. However, if your intention was to use the variable from the outer scope, then you could consider it a logical error.

but can the compiler really mess things up

No.

The problem with shadowing is that it can be hard to keep track of for the programmer. It is trivial for the compiler. You can find plenty of questions on this very site, stemming from confusion caused by shadowed variables.

It is not too difficult to grok which expression uses which variable in this small function, but imagine the function being dozens of lines and several nested and sequential blocks. If the function is long enough that you cannot see all the different definitions in different scopes at a glance, you are likely to make a misinterpretation.

declaration of 'count' hides previous local declaration 

This is a somewhat useful compiler warning. You haven’t run out of names, so why not give a unique name for all local variables in the function? However, there is no need to treat this warning as an error. It is merely a suggestion to improve the readability of your program.

In this particular example, you don’t need the count in the outer scope after the inner scope opens, so you might as well reuse one variable for both counts.

Is it worth it to change and fix the variable names

Depends on whether you value more short term workload versus long term. Changing the code to use unique, descriptive local variable names is “extra” work now, but every time someone has to understand the program later, unnecessary shadowing will increase the mental challenge.

Leave a Comment