使变量忘记之前的值
Make variables forget the previous values?
我遇到了一个很烦人的问题。
首先,我写了一个只运行一次的程序,一切都很完美,直到我决定让它在用户输入的情况下可重新执行。
现在我有大麻烦了。当我重新执行程序时,由于变量没有重新初始化自己,它陷入了错误的switch或if语句。来描绘它:
// Libraries and other stuff
int numA, numB, numC;
char charA = 'A', charB = 'B', charC = 'C';
int main() {
do {
// Randomly assigning some numbers between 1-3 range into numA, numB and numC
...
// Converting the integers above into chars depending on the random numbers
switch (numA)
{
case 1:
numA = charA;
break;
case 2:
numA = charB;
break;
case 3
numA = charC;
break;
}
switch (nu...
...
// A lot of IFs and SWITCHs that consistently changes the values above within themselves.
...
// Taking 1 input from user to re-execute the program
} while (input == 1)
return 0;
}
我知道我一开始没有正确初始化变量,把一切都搞砸了,但是当我开始创建它时,我不打算让它重新执行,现在我正在寻找最佳的逃避方式。我能不能让变量忘记它们之前携带的值?或者我真的需要从头开始重新初始化所有东西吗?
将变量的声明移到循环内的作用域中,以便每次循环时重新初始化它们。
int main() {
do {
//new scope
{
int numA, numB, numC;
char charA = 'A', charB = 'B', charC = 'C';
// Randomly assigning some numbers between 1-3 range into numA, numB and numC
...
// Converting the integers above into chars depending on the random numbers
switch (numA)
{
case 1:
numA = charA;
break;
case 2:
numA = charB;
break;
case 3
numA = charC;
break;
}
switch (nu...
...
// A lot of IFs and SWITCHs that consistently changes the values above within themselves.
...
// Taking 1 input from user to re-execute the program
}//end of scope
} while (input == 1)
然而,你应该明白,使用未初始化的变量是未定义的行为,应该始终避免。
你的字符变量初始化(char charA = 'charA'
)是完全无效的。您不能在一个字符变量中存储6个字符串(5个字符和空终止符)。你应该使用char*
或者这是一个简单的排版错误,它应该是char charA = 'A'
。
您将所有字符初始化为'c'。当你将所有字符初始化为'charA', 'charB' &'charC',但在初始化字符时,它只需要一个字符,如char ch1= '6', ch2='n' ;
因为所有的初始化式都有一个共同的第一个字母,那就是'c'。这就是为什么所有初始化为'c'。
还有,当()的()时,你忘了在后面加分号。此外,您正在使用numA作为开关控制变量。,在switch语句中,您正在更改numA中的值。这不是错误的做法,而是不好的做法。很抱歉很多编辑,因为我在stackexchange应用程序上,我需要多次看到问题。
相关文章:
- 在内存不足之前,我可以声明多少个 const 变量?
- 为什么在分配给成员变量之前获取unique_ptr的返回是一个问题?
- 如何在传递给 C/C++ 宏之前解析 int 变量?
- 如何在全局变量的构造函数之前运行函数
- 如果一个变量在它之前释放了另一个(相同的数据类型)变量,如何将其分配给内存?
- 我可以在初始化之前使用 std::array 成员变量中的 data() 指针吗?发出警告
- 从其他类声明类类型变量会给出 C2143 错误(在"*"之前缺少";")
- 局部变量 'sp' 在被读取之前在所有路径中重新分配
- 在 main 之前调试全局变量的赋值
- 如何使用GDB跟踪Main()之前初始化的所有静态全局变量
- 父级的静态变量是否保证在子级的静态变量之前初始化?
- 如果结果存储在变量中forward_as_tuple然后在 std::apply 中使用之前丢失右值引用
- 在结构声明的分号之前声明的结构变量是否为全局变量
- 为什么在执行条件变量通知之前我们需要一个空的 std::lock_guard?
- C++ 在知道变量类型之前使用自动定义的变量
- 如何在任何其他全局变量或静态变量之前创建/构造类实例
- 以下代码运行后,如何在程序再次运行之前清除用户声明的变量 empName
- 是否有任何方法可以在初始化之前更改变量的类型,您可以用示例解释
- 静态变量需要在MAIN处理ARGV参数之前进行初始化
- 使变量忘记之前的值