Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
I sure hope this is cool, coz it took its time
#40
Quote:Don't use global vars/arrays. Wink

Like everything else, the purpose for which a global variable is used is more important than stylistic conventions.
There are a number of very sane reasons for using a global variable.

1. The variable is truly used globaly in the program. If various routines all rely on a particular variable that is not functionally used as a parameter, it makes sense to use a global variable.
For example, if several screen output routines refer to some sort of color scheme, a global variable can be useful.

2. Speed and memory considerations. Parameters passed to a function or subroutine are placed on the stack. This takes time. Furthermore, to access variables by reference they must be dereferenced every time they are used, which takes time. If a routine is called rather frequenctly, replacing some parameters with global variables can save you many many many clock cycles when your program is executed.
As for memory, consider recursive functions.

FUNCTION EXMPL(X AS INTEGER, Y AS INTEGER) AS INTEGER
IF Y>0 THEN
EXMPL=0
ELSE
EXMPL=X+EXMPL(X,Y-1)
END IF
END FUNCTION

This rather useless routine (which recursively calculates X * Y for positive values of Y) needs 4 bytes of stack space for passing parameters every time it is invoked. If 1000 was passed as Y, that works out to 4000 bytes. But the X value passed to each iteration never changes. If a global variable had been used in place of X, for the same value of Y the parameters on the stack would only amount to 2000 bytes, effectively nearly doubling (the stack also contains other information) the upper bound on the Y parameter at which you'd have stack overflow issues.

Now it is true that global variables can make a program more difficult to read, and with poorly chosen names can cause conflicts with other code modules, but in certain contexts that are really useful.
Reply


Messages In This Thread
At a second nazar upon it... - by Pc72 - 11-27-2005, 02:44 AM
I sure hope this is cool, coz it took its time - by RyanKelly - 01-15-2006, 05:11 AM

Forum Jump:


Users browsing this thread: 1 Guest(s)