C++ 变量初始值不为0?

问题描述

在题目 Leetcode 806. 写字符串需要的行数 中发现一个问题。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<int> numberOfLines(vector<int>& widths, string s) {
int l=1,u=0;
for (auto &c:s){
if ((u+widths[c-'a'])>100){
u=widths[c-'a'];
l++;
}
else{
u+=widths[c-'a'];
}
}
return vector<int>{l,u};
}
};
中的第6行 int l=1,u=0;。其中u是非初始化为0将会影响结果。 当没有初始化为0的时候,u的初始值有一定概率是其他值。

这是为什么呢?

实际上在C++的变量初始化中,只有静态变量和全局变量,储存在stack中。而局部变量和动态变量储存在heap中,其初始值并没有规定。

而在Leetcode中,我们将Solution写在非main function的函数中。这样里面的变量都是局部变量,那么就必须要初始化了。

网友:定义变量行记着初始化。

养成好习惯。