Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Understanding scope of variables
#1
Hi everyone,

In ZXBASIC, is this a valid program?

Code:
function myFunction( name$ as string ) as uinteger     dim length, n as ubyte     dim total as uinteger = 0     length = len(name$)     if length=0 then return total     end if     for n = 0 to length-1 total = total + code(name$(n))     next n         return total end function REM Main program dim n as ubyte dim ans as uinteger n = 14 ans = myFunction("Hello") print "Answer = " + str$(ans) print "n = " + str$(n) stop

I have a variable labelled 'n' in both the top-level program and a function. I believe, in the function, 'n' is a different, locally defined variable, which is deleted when the function ends.

Would the same work, if I replaced the function with a subroutine (accepting I couldn't return an answer in the same way)?

I ask as I am seeing unexpected behaviour in my program (not the one above, a much longer program) and one possibility is that I'm using the same variable names for different entities in both the top-level program and subroutines.

Thanks in advance for any help
Reply


Messages In This Thread
Understanding scope of variables - by georgeo - 2021-03-11, 02:51 PM
RE: Understanding scope of variables - by georgeo - 2021-03-12, 12:13 AM
RE: Understanding scope of variables - by boriel - 2021-03-12, 11:32 PM
RE: Understanding scope of variables - by boriel - 2021-03-12, 11:26 PM
RE: Understanding scope of variables - by georgeo - 2021-03-13, 11:48 AM

Forum Jump:


Users browsing this thread: 1 Guest(s)