修改参数“按值传递'函数内,并使用他们作为本地变量 [英] Modifying arguments 'passed by value' inside a function and using them as local variables

查看:161
本文介绍了修改参数“按值传递'函数内,并使用他们作为本地变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了一些code中传递由值函数的参数已被修改或分配一个新的值,并使用像一个局部变量。

I have seen some code in which the arguments passed to the function by value was being modified or assigned a new value and was being used like a local variable.

这是一个好的事情?是否有这样做的任何陷阱还是确定为code这样?

Is it a good thing to do? Are there any pitfalls of doing this or is it Ok to code like this?

推荐答案

从本质上讲,一个函数的参数是一个局部变量,所以这种做法是不坏原则。

Essentially, a parameter of a function is a local variable, so this practice is not bad in principle.

在另一方面,这样做可能会导致维护问题。如果另一个程序员后来出现时,他可能希望变量来保存价值的传递和变化将导致的错误。

On the other hand, doing this can lead to maintenance headaches. If another programmer comes along later, he might expect the variable to hold the passed in value, and the change will cause a bug.

有关重用变量的一个理由是内存使用效率的一种错误的概念。实际上,它不能提高工作效率,并且可以减少它。其理由是,如果它是在两个不同的时间使用相同的寄存器两个不同的变量有用的编译可以自动检测,并且将做到这一点,如果它是更好。但程序员不应该让编译器决定。这将限制选择的编译器可以做到的。

One justification for reusing the variable is for a misguided notion of efficiency of memory usage. Actually, it can't improve efficiency, and can decrease it. The reason is that the compiler can automatically detect if it is useful to use the same register for two different variables at two different times, and will do it if it is better. But the programmer should not make that decision for the compiler. That will limit the choices the compiler can make.

最安全的做法是使用一个新的变量,如果它需要一个新的价值,并依靠编译器,使之高效。

The safest practice is to use a new variable if it needs a new value, and rely on the compiler to make it efficient.

这篇关于修改参数“按值传递'函数内,并使用他们作为本地变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆