对初始化时使用的未初始化局部变量感到困惑
Confused on uninitialized local variable being used when initialized?
当我相信我已经初始化时,我收到一个未初始化的局部变量错误。该错误读取正在使用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;
相关文章:
- 未初始化的变量有什么危险
- 使用的未初始化局部变量'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++构造函数:在初始化器列表之前初始化局部变量
- 如何初始化局部联合变量
- 实际初始化的未初始化局部变量
- 收到未初始化局部变量的警告