Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Variable as a reference or value to a function
#14
Functions will pass by reference in the exact same manner as subs.  The main rule of thumb is that variable types *must* match to pass.

Examples:
Code: (Select All)
DIM x AS INTEGER
x = 0
PRINT Foo(x)
PRINT Foo(x)
PRINT Foo(x)

FUNCTION Foo (X AS INTEGER)
  X = X + 1
  Foo = 2 * X
END FUNCTION

Now, the above will print 2, 4, 6 onto the screen, as the value of X changes and is passed back to the main routine with each run of the function.


Code: (Select All)
DIM x AS _FLOAT
x = 0
PRINT Foo(x)
PRINT Foo(x)
PRINT Foo(x)

FUNCTION Foo (X AS INTEGER)
  X = X + 1
  Foo = 2 * X
END FUNCTION

And the above will print 2, 2, 2 on the screen, as the function Foo uses an Integer, and the main module is passing a _FLOAT.  The two variable types aren't the same, so the value won't pass by reference.

For SUBs and for FUNCTIONs, variables pass by reference as long as the types match.
Reply


Messages In This Thread
RE: Variable as a reference or value to a function - by SMcNeill - 07-18-2022, 02:39 PM



Users browsing this thread: 4 Guest(s)