Global variables (Scope?)

Discussions about the BBC BASIC language, with particular reference to BB4W and BBCSDL
zeynel1
Posts: 21
Joined: Sun 15 May 2022, 11:35

Global variables (Scope?)

Post by zeynel1 »

This is newbe question.

Code: Select all

      
      REM Period of earth skimming satellite

      K0=FN_EarthSkimming(Radius_Earth)
      PRINT "Earth skimming satellite Period = ";K0

      END

      DEF FN_EarthSkimming(R)
      =(R^3/K0)^0.5

      PRINT "K0 is = ";K0
How can I use K0 globally?

Last line does not print.

Thanks
DDRM

Re: Global variables (Scope?)

Post by DDRM »

Hi Zeynel1,

By default, variables ARE global, unless they are parameters of a function/procedure, or you declare them as local: in your program K0 is a global variable.

There are a number of issues here.

1) The PRINT line at the end never gets reached: it comes after the END, and is not part of FN_Earthskimming, so it is floating in space!

2) What your program does is to call FN_Earthskimming, and assign the value to K0. Unfortunately, you have not defined the variable Radius_Earth, so it fails. You need to define it first.

3) Your FN_Earthskimming uses K0, but at this stage it hasn't been assigned (because the function has to execute before its value can be assigned to K0), so it has the default value 0, so the program fails with a "divide by zero" error.

So we could go for a version like this:

Code: Select all

      REM Period of earth skimming satellite

      Radius_Earth = 6400
      K0 = 5
      K1=FN_EarthSkimming(Radius_Earth)
      PRINT "Earth skimming satellite Period = ";K1

      PRINT "K0 is = ";K0

      END

      DEF FN_EarthSkimming(R)
      =(R^3/K0)^0.5
Now we are defining Radius_Earth and K0 before using them. You can see that K0 is acting as a global variable, since it works inside the function. I've changed the result of the function to K1 so you can see it hasn't changed the value of K0. I've moved the floating print statement to before the END, so now both get executed.

As an aside, it would be better practice to pass all values your function needs in as parameters, rather than relying on global variables. That makes the function much easier to use again, since you know exactly what you are relying on for it to work.

Hope that's helpful!

D
zeynel1
Posts: 21
Joined: Sun 15 May 2022, 11:35

Re: Global variables (Scope?)

Post by zeynel1 »

Great! Thanks for the detailed answer, that was helpful.