Global variables inside Procedures

Just starting out? Need help? Post your questions and find answers here.
User avatar
VB6_to_PBx
Enthusiast
Enthusiast
Posts: 617
Joined: Mon May 09, 2011 9:36 am

Global variables inside Procedures

Post by VB6_to_PBx »

is it OK to place Global variables inside Procedures ?

some of these same Global variables would then be accessed in other Procedures in my Program .

anyone see potential problems with doing this ?
 
PureBasic .... making tiny electrons do what you want !

"With every mistake we must surely be learning" - George Harrison
User avatar
skywalk
Addict
Addict
Posts: 3972
Joined: Wed Dec 23, 2009 10:14 pm
Location: Boston, MA

Re: Global variables inside Procedures

Post by skywalk »

Why not?
I put many def's in Main() or Init().
The nice thing about standards is there are so many to choose from. ~ Andrew Tanenbaum
User avatar
spikey
Enthusiast
Enthusiast
Posts: 581
Joined: Wed Sep 22, 2010 1:17 pm
Location: United Kingdom

Re: Global variables inside Procedures

Post by spikey »

You should be aware that there is the potential to create accidentally a scope ambiguity bug:-

Code: Select all

Procedure P1()
  
  V = 1
  
  Debug V
  
EndProcedure

Procedure P2()
  
  Global V.I 
  
  Debug V
  
EndProcedure

P1()
P2()

Debug V
If you run this code you will get the output:-

Code: Select all

1
0
0
The variable V isn't truly global despite appearing to be. P1 will implicitly create a local variable, which will be inaccessible to other procedures.

(Putting EnableExplict at the top of your code will detect this error, but if your code isn't currently written to allow that you'd need a refactor).
Little John
Addict
Addict
Posts: 4519
Joined: Thu Jun 07, 2007 3:25 pm
Location: Berlin, Germany

Re: Global variables inside Procedures

Post by Little John »

User avatar
VB6_to_PBx
Enthusiast
Enthusiast
Posts: 617
Joined: Mon May 09, 2011 9:36 am

Re: Global variables inside Procedures

Post by VB6_to_PBx »

Little John wrote:viewtopic.php?f=13&t=54221
from Fred :
Global is OK in procedures
i'm doing something like this ... i call the 1st Procedure which holds the Global variables
then call the other Procedures that calculate data

Code: Select all

EnableExplicit 

Procedure SetGlobalVar()
  Global var=1
EndProcedure

Procedure ShowGlobalVar()
  Debug var
EndProcedure


SetGlobalVar()
ShowGlobalVar()
 
PureBasic .... making tiny electrons do what you want !

"With every mistake we must surely be learning" - George Harrison
Post Reply