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 - 03-11-2021, 01:51 PM
RE: Understanding scope of variables - by georgeo - 03-11-2021, 11:13 PM
RE: Understanding scope of variables - by boriel - 03-12-2021, 10:32 PM
RE: Understanding scope of variables - by boriel - 03-12-2021, 10:26 PM
RE: Understanding scope of variables - by georgeo - 03-13-2021, 10:48 AM

Forum Jump:


Users browsing this thread: 3 Guest(s)