Using function arguments as local variables

前端 未结 9 1382
野的像风
野的像风 2020-12-30 03:57

Something like this (yes, this doesn\'t deal with some edge cases - that\'s not the point):

int CountDigits(int num) {
    int count = 1;
             


        
9条回答
  •  长情又很酷
    2020-12-30 04:27

    I think the best-practices of this varies by language. For example, in Perl you can localize any variable or even part of a variable to a local scope, so that changing it in that scope will not have any affect outside of it:

    sub my_function
    {
        my ($arg1, $arg2) = @_;    # get the local variables off the stack
    
        local $arg1;    # changing $arg1 here will not be visible outside this scope
        $arg1++;
    
        local $arg2->{key1};   # only the key1 portion of the hashref referenced by $arg2 is localized
        $arg2->{key1}->{key2} = 'foo';   # this change is not visible outside the function
    
    }
    

    Occasionally I have been bitten by forgetting to localize a data structure that was passed by reference to a function, that I changed inside the function. Conversely, I have also returned a data structure as a function result that was shared among multiple systems and the caller then proceeded to change the data by mistake, affecting these other systems in a difficult-to-trace problem usually called action at a distance. The best thing to do here would be to make a clone of the data before returning it*, or make it read-only**.

    * In Perl, see the function dclone() in the built-in Storable module.
    ** In Perl, see lock_hash() or lock_hash_ref() in the built-in Hash::Util module).

提交回复
热议问题