未初始化的本地变量' lc'使用但我初始化它

时间:2018-01-05 08:25:02

标签: c++ initialization

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

任务是编写一个带布尔函数的程序,如果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;
}

所以,你能告诉我,我在哪里弄错了变量&#39; lc&#39;为什么编译器会告诉我&#34;未初始化的局部变量&#39; lc&#39;使用&#34;

3 个答案:

答案 0 :(得分:1)

您尚未初始化 lc,但已宣布

初始化变量意味着给它一个初始值(你应该总是这样做):

int lc = 0;

答案 1 :(得分: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 ++中则不然 - 至少在这种情况下不是这样(int static存储持续时间是零初始化的。)

答案 2 :(得分:0)

初始化 您在此处所做的事情。正如amc176所述,你只有声明它。

声明变量lc时,内存将保留在堆栈中。保留的内存量取决于数据类型(char将占用比int更多的内存。

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

相关问题