is it good or bad to reuse the variables?

后端 未结 9 1989
灰色年华
灰色年华 2020-12-17 15:03

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;

  //..
         


        
相关标签:
9条回答
  • 2020-12-17 15:26

    Put it this way - how would you like it if I wrote a big pile of undocumented, complex code in such a way and, then, you get the job of maintaining/enhancing it.

    Please do not do such a thing, ever :)

    0 讨论(0)
  • 2020-12-17 15:41

    Only drawback is readability of your code.

    Reusing variables you are saving memory.

    Speed is not affected (unless you have to use more instructions in order to reuse variable).

    0 讨论(0)
  • 2020-12-17 15:43

    As with almost everything in programming, it depends on the situation.

    If you're reusing the same variable for different purposes, then it makes your code less readable and you shouldn't be doing it. If the purpose is the same (e.g. loop counters), then you can reuse with no problem since this isn't making your code less readable.

    Reusing a variable will avoid reserving space in the stack, which results in a faster (you don't waste time reserving space in stack and pushing the value) and less memory consuming (you're not storing it in the stack) program. But this benefits are absolutely negligible in the whole program context, and also relative to architecture, language and compiler. So I would worry more about readability than this tiny benefits.

    0 讨论(0)
提交回复
热议问题