是好还是坏重用的变量? [英] is it good or bad to reuse the variables?

查看:128
本文介绍了是好还是坏重用的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道它是好还是坏(或无所谓),如果我重复使用的变量名尽可能?例如:

I wonder if it is good or bad (or does not matter) if I reuse the variable names as much as possible? for example

int main(void){
  //...
  int x=0;

  //..
  x = atoi(char_var);

  //..

  for (x=0; x<12; x++){
   //...
  }

  //..
  x = socket(...)
  if(x<0){
  //...
  }

  for(x=0;x<100;x++{
  //...
  }

  return 0;
}

可以用来代替另一个变量X 以上(可能是可读性更好),但我不知道它是否会提供给我任何的好处的二进制尺寸,性能,还是别的什么?

Another variables could be used instead of x above (might be better for readability), but I wonder if it would provide me any benefit for the binary size, performance, or anything else?

推荐答案

在总体上是实践很差重用变量名用于不同的目的 - 如果别人需要稍后维护您的code的人都会有找在code这些上下文切换,其中 X 现在突然意味着其他的东西比什么该行code之前的意思。

In general it's very poor practice to reuse variable names for different purposes - if someone else needs to maintain your code later on the person will have to find these "context switches" in your code where x now suddenly means something other than what it meant before that line of code.

您可能会得到一些节省内存,但是相对于它介绍了它的建议针对的问题,那是那么小。 (阅读下面的编辑也。)

You may get some memory savings but that's so small compared to the problems it introduces that it's advised against. (Read the edit below, too.)

通常情况下它也建议不要超过循环计数器使用1个字符的变量名其他。有人可能会说 X 也有可能是X坐标,但是我会用一些preFIX或更长的名称在这种情况下。单字母变量名是太短给一个变量的目的,有意义的提示。

Typically it's also recommended not to use 1-character variable names for other than loop counters. One could argue that x could also be an X coordinate but I'd use some prefix or a longer name in that case. Single-letter variable names are too short to give meaningful hints about the purpose of a variable.

修改:为一些意见(和一些其他的答案)指出,潜在的节省内存(如果有的话)取决于编译器有多好。写得很好的优化编译器可能会发现两个变量有没有重叠的寿命,所以它们只是无论如何分配一个变量插槽。最终的结果将是没有运行时获得更谈不上维护源$ C ​​$ C。这只是加强了论据:不要重复使用变量

Edit: as several comments (and some of the other answers) pointed out, the potential memory savings (if any) depend on how good the compiler is. Well-written optimizing compilers may realize that two variables have no overlapping lifetimes so they only allocate one variable slot anyway. The end result would be no run-time gain and still less maintainable source code. This just reinforces the argument: don't reuse variables.

这篇关于是好还是坏重用的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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