对初始化时使用的未初始化局部变量感到困惑

Confused on uninitialized local variable being used when initialized?

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

当我相信我已经初始化时,我收到一个未初始化的局部变量错误。该错误读取正在使用wk1未初始化的局部变量(它是 wk1-wk5)。

这是代码:

#include <iostream>
using namespace std;
const double tax = 0.14;
int main()
{   
    int wk1,wk2,wk3,wk4,wk5;
    wk1,wk2,wk3,wk4,wk5 = 0;
    int thours = wk1 + wk2 + wk3 + wk4 + wk5; <------------ This is the error line.
    thours = 0;
    double payrate;
    payrate = 0;
    double gross = thours * payrate;
    double taxes = tax * gross;
    double net = gross - taxes;
    double clothes = 0.10 * net;
    double supplies = 0.10 * net;
    double remaining = net - clothes - supplies;
    double bonds = 0.25 * remaining;
    double pbonds = 0.50 * bonds;
    bonds = 0;
    gross = 0;
    net = 0;
    clothes = 0;
    supplies = 0;
    remaining = 0;
    cout << "Please enter the payrate for employee." << endl;
    cin >> payrate;
    payrate = 0;
cout << "Please enter employee's total hours for week one:" << endl;
cin >> wk1;
wk1 = 0;
    cout << "Please enter employee's total hours for week two:" << endl;
    cin >> wk2;
    wk2 = 0;
    cout << "Please enter employee's total hours for week three:" << endl;
    cin >> wk3;
    wk3 = 0;
    cout << "Please enter employee's total hours for week four:" << endl;
    cin >> wk4;
    wk4 = 0;
    cout << "Please enter employee's total hours for week five:" << endl;
    cin >> wk5;
    wk5 = 0;
    cout << "Here is income before taxes: " << gross << endl;
    cout << "Here is income after taxes: " << net << endl;
    cout << "Here is clothes and accesories: " << clothes << endl;
    cout << "Here is School supplies: " << supplies << endl;
    cout << "Here is personal bonds: " << bonds << endl;
    cout << "Here is parents bonds: " << pbonds << endl;
    return 0;
}
wk1,wk2,wk3,wk4,wk5 = 0;

此行是逗号运算符表达式,等效于:

wk5 = 0;

因为像wk1这样的表达没有副作用。只有变量wk5被赋值,其他变量仍未初始化。你可以做:

wk1 = wk2 = wk3 = wk4 = wk5 = 0;