Computer Science Canada

Exporting Variables from Procedures

Author:  Mr. T [ Sun Jun 04, 2006 2:27 pm ]
Post subject:  Exporting Variables from Procedures

code:

procedure test (var a : int)
    a := 3
end test

put a

Clearly this won't work because the variable 'a' only exists in its own little procedure world. But let's say there's an instance when i need to export a variable (along with its value) from a procedure. How would I go about doing this?

Author:  wtd [ Sun Jun 04, 2006 2:39 pm ]
Post subject: 

Ok, so you have...

code:
procedure test (var a : int)
    a := 3
end test


Now, let's declare a variable.

code:
var foo : int := 42


Now, let's pass it to the procedure.

code:
test (foo)


Now, let's see what the value of "foo" is.

code:
put foo

Author:  Mr. T [ Sun Jun 04, 2006 2:45 pm ]
Post subject:  Alex's Opinion

Ok, but doesn't doing that render a := 3 inside the procedure useless?

Author:  Cervantes [ Sun Jun 04, 2006 3:25 pm ]
Post subject: 

No, it is not useless. It will change the value of the variable you pass to it (foo, in this case).

However, this is a terrible practice. Parameters are good, but when the procedure is allowed to change the value of the variables you pass in as parameters, you've got a situation almost as bad as global variables.

If you want to change the value of 'foo', don't do it from within the procedure. Rather, make your procedure a function and use that.

code:

function test : int
    result 3
end test
var foo : int := 42
put foo
foo := test
put foo

output wrote:

42
3

Author:  Mr. T [ Sun Jun 04, 2006 3:36 pm ]
Post subject:  Alex's Opinion

Thanks. Razz


: