warning: uninitialized variable //But I have initialized ! C++ Compiler bug?

后端 未结 5 1230
夕颜
夕颜 2021-01-05 13:56

Iam trying to compile this program but i get warning and when i run vc++ 2010 debugger pops up : ( Here is my code :

#include 
using namespa         


        
5条回答
  •  一个人的身影
    2021-01-05 14:54

    You have declared them, but not initialized them. Simply write int minn = 0, index = 0; to avoid the warning. If you don't initialize a variable, its default value is whatever was at that location in memory already; usually garbage.

    The thing is, if num is negative, then neither of the for loops in your min() function will execute, and so minn and index will not have been assigned values. The if(i == num) test also won't break out of the function and prevent this from happening. So the last two lines of the function will have completely undefined results.

    Sometimes there really isn't a path for the variables to be used uninitialized, though; sometimes the compiler just isn't quite smart enough to figure out all the subtleties. Just give them an initial value to avoid the warning.

提交回复
热议问题