关于C++局部变量初始化问题
大家讲道理
大家讲道理 2017-04-17 13:27:32
0
3
551

如果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;
}


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

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(3)
小葫芦

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.

阿神

Static int variables are automatically assigned a value of 0

Ty80

This error report was added by VS kindly for you

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!