警告:未初始化的变量//但我已初始化! C ++编译器错误? [英] warning: uninitialized variable //But I have initialized ! C++ Compiler bug?

查看:137
本文介绍了警告:未初始化的变量//但我已初始化! C ++编译器错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Iam试图编译这个程序,但我得到警告,当我运行vc ++ 2010调试器弹出:(
这里是我的代码:

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

#include <iostream>
using namespace std;
int num;
int min(int mas[])
{
    int i,minn,index;        /* But I have declared them : (((( */
    for(i=0;i<num;i++)
        {
            if(mas[i]!=0)minn=mas[i];
            break;
        }
    if(i==num) return 0;
    for(i=0;i<num;i++)
       if(mas[i]!=0 && minn>mas[i])
        {
            minn=mas[i];
            index=i;
        }

    mas[index]=0;
    return minn;
}

int main()
{
    cin>>num;
    int *array=new int[num];  int tmp;
    tmp=min(array);

}

这是一个编译器日志:

prog.cpp: In function ‘int min(int*)’:
prog.cpp:6: warning: ‘index’ may be used uninitialized in this function
prog.cpp:6: warning: ‘minn’ may be used uninitialized in this function

?或者它是编译器错误? :)
谢谢:)

What i am doing wrong ? or its is compiler bug ? :) Thank you :)

推荐答案

您已经 em>初始化。只需写 int minn = 0,index = 0; 即可避免警告。如果你不初始化一个变量,它的默认值就是在内存中的那个位置;通常是垃圾。

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.

事情是,如果 num 是负数, c $ c> min()函数将执行,因此 minn index 未分配值。 if(i == num)测试也不会突破该功能,并防止这种情况发生。因此,函数的最后两行将具有完全未定义的结果。

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.

这篇关于警告:未初始化的变量//但我已初始化! C ++编译器错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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