使用了未初始化的局部变量"lc",但我对其进行了初始化

Uninitialized local variable 'lc' used but I initialized it

本文关键字:初始化 局部变量 lc      更新时间:2023-10-16

我想检查我在编程考试中写的内容是否至少有效。事实证明,事实并非如此。而且我不明白为什么它不起作用。

任务是编写一个带有布尔函数的程序,如果 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占用更多的内存)。

但是,如果您没有为该变量提供初始值(即初始化它),则数据类型的初始值将恰好是该特定内存中存在的值。这就是您的编译器抱怨的原因。