Unitialized Variables in C++

耗尽温柔 提交于 2021-02-10 08:28:15

问题


The question that was put forth to me was:

What will the value of uninitialized variables be in C++? Do we have to initialize all variables? What would be the rule for initializing variables?

I've looked in my text as well as another text that I have on hand and can't seem to find the answer. Here's what I've attempted:

The value of uninitialized variables in C++ depends on the previous value stored in the memory that the uninitialized variable is assigned to. Initializing all variables is not a requirement, e.g. a variable does not need to be initialized if the variable will immediately be assigned a value via user input. Good programming practice should be to initialize a variable and if a variable is uninitialized, then comments should explain the reasoning behind leaving the variable uninitialized.

Am I missing something? Is their a resource anyone could point me to? Is there a "rule" to variable initialization that I missed? Thank you.


回答1:


Generally, you have no idea what is stored in an uninitialized variable so it is always a good idea to initialize variables. This way you can avoid possible confusion later on; for example, if you went to print out a variable later on in your program for debugging (and you hadn't initialized it yet) it would likely print out some strange value.

If you want some more info, it looks like your question was also answered here: http://www.cplusplus.com/forum/general/62807/




回答2:


Pretty good. Don't forget that variables with global scope (globals and static locals) are initialized to zero at program initialization.




回答3:


For global and static variables including static class members, they will be initialized to zero/NULL. Everything else is usually undefined, meaning can be anything. An exception are in high security environments, the system may clear released memory, in which case if you use it, it will be all zeroes. Another exception can be debug builds, where special magic numbers are sometimes used to initialize memory and variables as a way to detect some common programming errors.




回答4:


The variable is declared but is not set to a definite known value before it is used. It will have some value, but not a predictable one. I suggest you to take a look at this page http://www.learncpp.com/cpp-programming/eight-c-programming-mistakes-the-compiler-wont-catch/



来源:https://stackoverflow.com/questions/33336641/unitialized-variables-in-c

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