3 ms·
The difference between a local variable and a function argument is that altering the argument has an effect outside the function, and that the effect is invisib
by mighty_bander 9y ago
The difference between a local variable and a function argument is that altering the argument has an effect outside the function, and that the effect is invisible in that calling the function doesn't tell you that it will change the argument's value. It is a minor sin in the case of e.g. massaging data to turn NaNs into 0s or provide default values. It is also fine in the case of performance-critical code: c string manipulation functions might move a pointer along the string's length. However it is much easier to program against a function which has a single predictable result, ideally the generation of a return value based on input. If you mess with a function's input, you had better a) document that fact and b) have a reasonable expectation that your consuming dev is going to read the documentation. C programmers have this one tiny luxury; authors of an npm package do not.
- emerged 9y agoOk sorry, I didn't make explicit an important bit -- from my perspective these variables are initialized by the callee but are otherwise local to the function. From a C perspective imagine them as function local variables which are contructed by the callee's parameters.
- adrianmonk 9y agoYou can't generalize across all languages that modifying an argument modifies something visible outside the function. It is true in languages that have pass by reference (C++ with &, Pascal, others) and it isn't true in languages which have pass by value (C, Java). And yes, passing a reference or pointer by value enables you to have effects that are visible outside the function, but if you copied the reference or pointer value to a local variable, you still could have effects visible outside the function, so that isn't a question of how arguments should be treated; it's a general question of how functions should behave.