1

sorry if the title is not very clear, I'm not sure how to say that... I often lost much time debugging because of a stupid mistake like this one:

for(int i=0;i<10;i++)
{
    ...
    for(int i=0;i<50;i++)
    {
         somearray[i]=x;
    }
    ...
}

Because I like small variable names, I even don't know why it's possible to do that in c++ isn't it useless ? Is there a way to ask visual c++ to alert about this multiple declaration ?

Thanks

justin
  • 104,054
  • 14
  • 179
  • 226
Entretoize
  • 2,124
  • 3
  • 23
  • 44
  • This code compiles without an error on Visual Studio??? The only way you wouldn't get an error (or a warning) on this is if you declare `int i` **before** the outer `for` loop, in which case - yes, no one's gonna warn you about it (because it is possibly what you meant to do). – barak manos Nov 26 '14 at 07:48
  • One way is to write small functions and refactor your function once it reaches say 80 lines. Such problems are more prominent in codes that span many 100s or even 1000s of line or when [arrow anti pattern](http://c2.com/cgi/wiki?ArrowAntiPattern) is practiced. – Mohit Jain Nov 26 '14 at 07:50
  • Yes it compiles... Yes I know I must split into small functions, I programmed calculator to much time :-) – Entretoize Nov 26 '14 at 07:55
  • @barakmanos: Why would this give an error? Why would there be a need to declare `int i` outside the for-loop? Defining `for (int i = ...` is perfectly normal, and gives you a variable with loop scope. – MSalters Nov 26 '14 at 08:02
  • Sure, it just increase the risk to make a human mistake for no gain in coding... – Entretoize Nov 26 '14 at 08:06
  • @MSalters: Oh yes, the declaration in the `for` line is actually within the `for` scope... my mistake, thanks... – barak manos Nov 26 '14 at 08:07

4 Answers4

1

You can test in VS using Analyzer Warning C6246.

You can also test using GCC or Clang using -Wshadow.

See also: Is there an equivalent of gcc's -Wshadow in visual C++

Community
  • 1
  • 1
justin
  • 104,054
  • 14
  • 179
  • 226
0

This is possible because names in inner scopes can hide names in outer scopes. Here, the two scopes are for loops, but the principle applies in general.

There are plenty of examples of this in Standard C++. For instance, there's a std::begin but also a std::string.begin. You can't really warn against this.

MSalters
  • 173,980
  • 10
  • 155
  • 350
0

According to my knowledge this can not be done as the given code component is valid in c++

tnishada
  • 1,315
  • 1
  • 16
  • 24
0

This is correct code in the sense, that the outer and inner i are two different variables. However, inside the inner loop you cannot refer to the outer i (which may or may not be necessary).

If your compiler doesn't give you a warning, you shoul increase your warning Level

MikeMB
  • 20,029
  • 9
  • 57
  • 102