Use arguments as variables. Should this really be allowed?

Might be a stupid question but I find it a bit confusing that this works:

f = {|in, variable|
	variable = in;
	variable.postln;
};
f.(0.5, 55);

The argument could be assigned something inside the function, thus overwriting the argument input. I.e. used as an undeclared variable. Isn’t this a bit to generous to allow, syntactically? Or are there situations where this is good/necessary?

For me, it’s “normal” and all the languages I know where variables are passed as values share the same behavior.

I’m expecting this

(
f = {|in, variable|
	variable = in;
	variable.postln;
};
)
a = 0.5;
b = 55;
f.(0.5, 55);
a.postln;
-> 0.5
b.postln;
-> 55
2 Likes

args and vars are both local variables. The only difference is that args are initialized from outside the function (by arguments) while vars can be initialized only within the function.

After that there is no difference.

The only difference is how they are initialized.

hjh

2 Likes

A use case my personal code is full of:

being able to check if the arg is nil, and if so, set it to something useful

I, too, think it’s ‘normal’ behavior in other programming languages (but don’t have a handy example, so ymmv)

Cheers,
eddi

https://soundcloud.com/all-n4tural
https://alln4tural.bandcamp.com

1 Like

Out of curiosity, what language do you usually program in that prohibits that? (You can make arguments const in e.g. in C++ and that will complain/error if you assign to it, but there’s no const in SC, as far as I know.)

1 Like

Thanks for claryfying. I kind of “knew” this but i guess i never thought about it before. But this makes sense now.

I don’t have much experience of other languages than SuperCollider so i don’t know. I trust you guys that i just have too adapt to the way things are. :slight_smile: