Home  >  Q&A  >  body text

关于C++局部变量初始化问题

如果num不给初值,编译的时候可以通过,显示的是warning,但是运行的时候就会出错,显示变量未定义。当变量为全局变量的时候,运行不会报错。这是说C++不会给局部变量赋初值么?还是说最开始可能是一个随机值?
环境VS2012
程序就是一个输入字符串,求元音字母的个数。

#include <iostream>
using namespace std;


int main()
{
    int num = 0;
    char ch;

    while(cin >> ch)
    {
        switch(ch)
        {
        case 'a':   case 'A':        case 'e':        case 'E':        case 'i':        case 'I':        case 'o':        case 'O':        case 'u':        case 'U':
            num++;
            break;
        default:
            break;
        }
    }
    cout << num;
}


如果点击忽略,然后结果输出的是负的超级大的数。

大家讲道理大家讲道理2714 days ago552

reply all(3)I'll reply

  • 高洛峰

    高洛峰2017-04-17 13:29:32

    Using uninitialized non-static local variables is undefined behavior.

    Non-static local variables of built-in types are uninitialized by default, their values ​​are random, and must be initialized before use.

    reply
    0
  • 阿神

    阿神2017-04-17 13:29:32

    Static int variables are automatically assigned a value of 0

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 13:29:32

    This error report was added by VS kindly for you

    reply
    0
  • Cancelreply