DEV Community

A Curious Learner
A Curious Learner

Posted on

Solve the error: redefinition of

Suppose we have such a segment of code:

int a[2];
int i=1;
for(int i=0;i<2;i++){
  a[i]=i;
}
Enter fullscreen mode Exit fullscreen mode

When we compile and write a piece of code, the compiler may successfully compile the program, or it may display an error message: redefinition of "i".
The situation depends on the type of compiler. Some compilers allow redefining a variable with the same name within a block of code enclosed in curly brackets. For example:

int i=1;
if(true){
  int i=3;
}
Enter fullscreen mode Exit fullscreen mode

In the above code, the variable i is defined twice, the second time we define i in the if block. But the compiler will still compile the program successfully, because this kind of compiler allows redefinition of variables in a segment of code inside the curly brackets, and the i inside the braces is invisible to the code outside the curly brackets, that is, the value of i outside the braces is still 1 instead of 3.
However, in the case of bad luck, some compilers will not allow us to redefine a variable that has already been defined in a for loop.

Top comments (1)

Collapse
 
pauljlucas profile image
Paul J. Lucas

It's not a redefinition of the same variable. It's the definition of a new variable in a nested scope that just so happens to have the same name. It's similar to:

int i;
{
    int i;
    // ...
}
Enter fullscreen mode Exit fullscreen mode

While legal, it's bad practice. Most compilers will offer a warning when doing this.