Should I worry about unused variables?

人走茶凉 提交于 2021-01-19 16:37:23

问题


I am working in large code base in C++, totaling approximately 8 million lines of code. In my application I have seen thousands of unused variables, which were reported by g++ but were ignored by my team. I want to take initiative for cleaning these variables but I need some info before working this issue.

Will there be any issues or disadvantages of having thousands of unused variables?

The compiler by default treats this as an ignored warning, but I believe we should treat warnings as errors. Is there any disaster which can occur if we ignore this warning?

Should we make the effort to rectify this problem or would it just be wasted effort?


回答1:


Assuming your variables are POD types like ints, floats etc, they are unlikely to have an effect on performance. But they have a huge effect on code quality. I suggest as you update your code to add new features, you remove the unused variables as you go. You MUST be using version control software in order to do this safely.

This is a not uncommon problem. As a consultant, I once reviewed a large FORTRAN codebase that contained hundreds of unused variables. When I asked the team who wrote it why they were there, their answer was "Well, we might need them in the future..."




回答2:


If you compile with optimizations on, the compiler will most likely simply remove the variables, just as if they aren't there. If you don't use optimizations, then your program will occupy additional extra storage space for the variables without using it.

It's good practice to not declare variables then not use them, because they might take up space and, more importantly, they clutter up your code, making it less readable.

If you have, say, 1000 unused ints, and an integer on your platform is 32 bits long, then you will, in total, use up 4K of extra stack space, with optimizations turned off.

If the unused variables are not arguments, then there should be nothing stopping you from removing them, as there's nothing you could break. You will gain readability and you will be able to see the other, more serious warnings that the compiler might produce.




回答3:


Unused variables are still allocated in memory. Removing them will free up memory.



来源:https://stackoverflow.com/questions/6088983/should-i-worry-about-unused-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!