如果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;
}
如果点击忽略,然后结果输出的是负的超级大的数。
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
This error report was added by VS kindly for you