[Solved] Is this supposed to be allowed?

New to FreeBASIC? Post your questions here.
Post Reply
noop
Posts: 130
Joined: Sep 18, 2006 10:29

[Solved] Is this supposed to be allowed?

Post by noop »

Hi,

is the following supposed to be allowed?

Code: Select all

sub test(byref x as integer)
    print x
    for i as integer = 0 to 0
        dim as integer x = 4
        print x
    next i
    if x = 3 then
        dim as integer x = 4
        print x
    end if
    print x
end sub


dim as integer x = 3
test(x)
sleep
Last edited by noop on Mar 15, 2016 10:03, edited 1 time in total.
fxm
Moderator
Posts: 12107
Joined: Apr 22, 2009 12:46
Location: Paris suburbs, FRANCE

Re: Is this supposed to be allowed?

Post by fxm »

Yes.
Inside each [for...next] / [if...end if] block, 'dim' defines a new local variable 'x' which is different from the external variable 'x'.

One can check it:

Code: Select all

sub test(byref x as integer)
    print @x, x
    for i as integer = 0 to 0
        dim as integer x = 4
        print @x, x
    next i
    if x = 3 then
        dim as integer x = 4
        print @x, x
    end if
    print @x, x
end sub

dim as integer x = 3
test(x)
sleep
noop
Posts: 130
Joined: Sep 18, 2006 10:29

Re: Is this supposed to be allowed?

Post by noop »

Interesting. Although it seems like a dangerous coding style. A compiler flag disallowing such behaviour would be nice.
Thanks for clearing this up fxm.
fxm
Moderator
Posts: 12107
Joined: Apr 22, 2009 12:46
Location: Paris suburbs, FRANCE

Re: [Solved] Is this supposed to be allowed?

Post by fxm »

This is only allowed in the -lang fb and -lang deprecated dialects, otherwise a compiler error 'error 4: Duplicated definition' is returned.

About that, there is already a note in documentation at page KeyPgDim:
.....
- In the -lang fb and -lang deprecated dialects, variables defined inside compound block statements (For..Next, While..Wend, Do..Loop, If..Then, Select..End Select, With..End With, Scope..End Scope) have local working scopes, and are visible only within these blocks.
.....
Post Reply