[AGS4 compiler] Possibility to redeclare a variable inside a loop

Started by Monsieur OUXX, Fri 01/08/2025 22:22:04

Previous topic - Next topic

Monsieur OUXX

The AGS4 compiler allows this:

Code: ags
int x=0; // declare outside loop
while(x!=1) {
  int x=0; // declare again inside loop, with same name
  x=1;
}

I cannot say for sure if the example above will loop infinitely because I don't remember the exact piece of code that made me notice the issue, but I definitely got indices mistakes caused by the fact that the inner variable was silently taking the spot of the outer variable with the same name.

I'm not sure what's allowed and not allowed in terms of re-declaring variables in inner blocks. I'm just reporting it in case it's an oversight.
 

Crimson Wizard

This is intended behavior, corresponding to a standard behavior of all the C-like languages (and maybe many others), where a local variable inside a block overrides a variable of same name outside of a block.

Similarly, it should be possible to have local variables, overriding global variables of the same name.

Monsieur OUXX

Quote from: Crimson Wizard on Fri 01/08/2025 23:11:41This is intended behavior, corresponding to a standard behavior of all the C-like languages

For over a decade I've been using IDEs and linters that will scream at you if you do that, so I confess I forgot that it was even possible. For inner blocks, yes. Local variables overriding global variables, yes. For a loop, I haven't seen that in a million years.

Thanks!
 

Crimson Wizard

Quote from: Monsieur OUXX on Today at 00:09:14For inner blocks, yes. Local variables overriding global variables, yes. For a loop, I haven't seen that in a million years.

But the loop is a type of inner block. For a compiler there's no difference whether it's inside a loop, or inside a "if", etc.

Whether compiler should warn users about such thing (when the variable of same name is used in loop's condition) is another question. Maybe it's possible to teach compiler to deduce what is used in a loop condition.

SMF spam blocked by CleanTalk