GOOC - Game Oriented Object C

GOOC - Game Oriented Object C

Next: Parameter Storage, Previous: Defining a Subroutine, Up: Subroutines
[Contents]

9.2. Subroutine Parameters

9.2. Subroutine Parameters

Function parameters can be any expression—a literal value, a value stored in a variable, an address in memory, or a more complex expression built by combining these.

From the callee's perspective, the (evaluated) parameter is a local copy of the value passed into the subroutine; you cannot change the value passed in by the caller by changing the local copy. sub Times2 (a) { a = a<<1 a = misc } ... x = 4.0 Times2(x) ... In that example, even though the parameter a is modified in the subroutine Times2, the variable x that is passed to the subroutine does not change.

If the value that you pass to a subroutine is a memory address (that is, a pointer), then you can access (and change) the data stored at the memory address. This achieves an effect similar to pass-by-reference in other languages, but is not the same: the memory address is simply a value, just like any other value, and cannot itself be changed. The difference between passing a pointer and passing an integer lies in what you can do using the value within the subroutine.

Here is an example of calling a function with a pointer parameter: this is not actually valid code yet lol sub Times2(a) { a[0] = a[0] << 1 } ... var foo = 4.0 Times2(&foo) ... Here we pass the memory location of the local variable foo to the subroutine Times2. The subroutine then dereferences the pointer (this can be achieved by simply accessing its first member as if it were an array), which gets the actual value stored at that address. That value is then multiplied by two (via left shift), and stored back as the first value of the "array".