Home
JAQForum Ver 24.01
Log In or Join  
Active Topics
Local Time 06:16 19 Nov 2025 Privacy Policy
Jump to

Notice. New forum software under development. It's going to miss a few functions and look a bit ugly for a while, but I'm working on it full time now as the old forum was too unstable. Couple days, all good. If you notice any issues, please contact me.

Forum Index : Microcontroller and PC projects : local variables

Author Message
crez

Senior Member

Joined: 24/10/2012
Location: Australia
Posts: 152
Posted: 08:40pm 04 Jun 2021
Copy link to clipboard 
Print this post

running the following

Option explicit
Dim a As integer
s1
End

Sub s1
Local b As integer
s2
End Sub

Sub s2
Local c As integer
a=1
b=1
c=1
End Sub


gives the error 'b is not declared' at line 14.
because sub s2 is called from within s1, I was expecting b would be declared, in the same way that a is available in s1. Apparently not. If I declare b in sub s1 using the DIM command, it becomes available in sub s2 but also the main program, which is not what I desired.
 
CaptainBoing

Guru

Joined: 07/09/2016
Location: United Kingdom
Posts: 2171
Posted: 08:51pm 04 Jun 2021
Copy link to clipboard 
Print this post

DIMed variables are global no matter where they are declared

I use this with my VB-a-like Split function. Because an array cannot be REDIMed, I ERASE it then DIM it inside a Function expecting it to be available outside the Sub/Function.



In the red boxes, the array is ERASEd and then DIMed in one of two places. The new array becomes available outside the Function. This simulates the VB REDIM statement.

If you only want that variable for s2, you can pass it in as an argument when you call it:

Sub s2(b as integer)
Print b


you then have a "b" variable available just to s2
.
Edited 2021-06-05 07:02 by CaptainBoing
 
JohnS
Guru

Joined: 18/11/2011
Location: United Kingdom
Posts: 4147
Posted: 09:34pm 04 Jun 2021
Copy link to clipboard 
Print this post

  crez said  running the following

Option explicit
Dim a As integer
s1
End

Sub s1
Local b As integer
s2
End Sub

Sub s2
Local c As integer
a=1
b=1
c=1
End Sub


gives the error 'b is not declared' at line 14.


LOCAL means lexically scoped to the enclosing SUB (or FUNCTION), as you've discovered.

(Many other languages do it that way, too.)

So, b is visible inside s1 but nowhere else.

John
Edited 2021-06-05 07:35 by JohnS
 
crez

Senior Member

Joined: 24/10/2012
Location: Australia
Posts: 152
Posted: 03:29am 05 Jun 2021
Copy link to clipboard 
Print this post

Thanks Captain and John.
   I'm a bit surprised this didn't trip me up earlier. Hopefully I remember it for next time .I have it working as I wanted by DIM at the start of the sub and ERASE at the end.

David
 
Print this page


To reply to this topic, you need to log in.

The Back Shed's forum code is written, and hosted, in Australia.
© JAQ Software 2025