[Gambas-user] Variable reinitialized at each iteration of a loop structure
Benoit Minisini
benoit.minisini at gambas-basic.org
Tue Mar 28 09:54:17 CEST 2023
Le 28/03/2023 à 01:00, Brian G a écrit :
> I have a question... as usual..
>
> When a variable is declared within a loop with an initial value, the
> value is reinitialized at each iteration of the loop.
> But when it is not provided with an initial value,it is not reset to
> zero at each iteration of the loop or when the loop is entered.
>
> If we view each loop structure as a closed block of code, would it not
> be more appropriate to initialize the variable upon entry to the block.
> And then have the loop structure return to just after the initialization
> sequence rather than the actual loop entry label.
>
> Also should not the variable declared in the block without an initial
> value be reinitialized to the default value as the block is entered.
>
> I do understand that the declaration of a variable within any block is
> for convenience, but if it is allowed should their values not follow
> some consistent rules?
>
> How hard is it to change the return/iteration point on a loop to just
> after variable initialization of contained variables?
> Or maybe I am just wrong about this?
>
As said in the thread:
Dim Var As Integer = 1
Is syntaxic sugar for:
Dim Var As Integer ' A declaration...
Var = 1 ' Plus a statement
But:
Dim Var As Integer
Is not an equivalent of:
Dim Var As Integer
Var = 0
Because the default zero value of the variable is not initialized by the
code but internally by the interpreter.
And as there is only function scope for variable declaration, you get
the behaviour you described.
Once explained, that behaviour is logical. It's surprising only if you
don't know how variable declaration is implemented.
As Jussi said, we can make:
Dim Var As Integer
an equivalent of:
Dim Var As Integer
Var = 0
when Var is not declared at the top of the function.
But then the declaration of a variable not on top of a function is not
the same as the declaration of a variable on top.
At the moment I'm not sure this cannot lead to some problems, so I will
wait and think a bit before deciding implementing it or not.
By the way, I almost never declare variables in the middle of a
function. It's always a source of confusion, sometimes bugs, and make
the code less readable.
Regards,
--
Benoît Minisini.
More information about the User
mailing list