使用了未初始化的局部变量"lc",但我对其进行了初始化
Uninitialized local variable 'lc' used but I initialized it
我想检查我在编程考试中写的内容是否至少有效。事实证明,事实并非如此。而且我不明白为什么它不起作用。
任务是编写一个带有布尔函数的程序,如果 2d 矩阵只有一行完全由负元素组成,则应返回 true 状态。
这是代码:
#include "stdafx.h"
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
bool cns();
const int n=5;
int a[n][n];
bool cns() {
int ts;
//!!!!
int lc; //!! I have initiated lc variable but still it does not work !!
//!!!
//standard 2d static quad matrix
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << "a[" << i << "][" << j << "]=" << endl;
cin >> a[i][j];
}
}
//check whether the sum of elements of the row is negative or not
for (int i = 0; i < n; i++) {
ts = 0; //temp sum
for (int j = 0; j < n; j++) {
ts += a[i][j]; //I thought what if sum of elements is negative then the whole row is negative too
if (ts < 0) { //I have just realized that is wrong
lc++; //counter of negative lines, which consist entirely of negative elements
}
}
}
//only one row should be whole negative
if (lc == 1) {
return true;
}
else {
return false;
}
}
int main()
{
int lc;
cout << cns << endl;
return 0;
}
那么,您能否告诉我变量"lc"在哪里出错,为什么编译器告诉我"使用了未初始化的局部变量'lc'"?
您尚未初始化lc
,但已声明它。
初始化变量意味着给它一个初始值(你应该总是这样做):
int lc = 0;
初始化变量本质上是给它一个初始值。
您对lc
的定义
int lc;
不初始化它。 由于它是自动存储持续时间的变量(即它是块的本地变量),因此不会初始化。
因此,访问其值会产生未定义的行为。
代码对lc
(在代码的第一组循环中)执行的第一件事是
lc++;
递增类型int
的变量需要在产生效果(执行递增操作)之前访问其值。 因此行为未定义。
因此,正在发出编译器警告。 若要消除警告,请在定义警告的位置对其进行初始化。 例如;
int lc = 42;
或者确保第一个操作是将其设置为有效值
int lc;
// later on the first thing ever done to lc is ...
lc = 47;
人们通常假设所有变量(基本类型,如int
)在没有显式初始化的情况下定义,其初始值为0
(零)。 在其他一些语言中是正确的,但在C++中并非如此 - 至少在这种情况下不是这样(static
存储持续时间的int
为零初始化)。
初始化不是你在这里所做的。如 amc176 所述,您仅声明了它。
当您声明变量lc
时,内存将保留在堆栈上。保留的内存量取决于数据类型(char
将比int
占用更多的内存)。
但是,如果您没有为该变量提供初始值(即初始化它),则数据类型的初始值将恰好是该特定内存中存在的值。这就是您的编译器抱怨的原因。
相关文章:
- 未初始化的变量有什么危险
- 使用的未初始化局部变量'Quick'
- C++如何通过"constructor initialization"初始化行变量?
- "local scope"中的 C++ 初始化静态变量
- 为什么我的 c++ 程序检查不是初始化的变量?
- 使用大括号或括号初始化成员变量
- 使用 std::ios_base::Init 正确初始化全局变量
- 'auto *x = new some_struct{};"是一个未初始化的变量?
- 是否可以将已经初始化的变量转换为 void*?
- Clang++ 6.0 内存清理器未报告返回值指示条件分支的函数中的未初始化局部变量
- 为什么默认情况下初始化局部变量
- 如果仅在 lambda 中使用,则不会在发布版本中初始化局部静态变量
- 对初始化时使用的未初始化局部变量感到困惑
- 如何在Qt(gcc 64位)中禁用自动初始化局部变量
- 在函数中初始化局部变量时出现问题
- 为什么VS编译器不会在C++上自动初始化局部变量?
- C++构造函数:在初始化器列表之前初始化局部变量
- 如何初始化局部联合变量
- 实际初始化的未初始化局部变量
- 收到未初始化局部变量的警告