0

我不太清楚我的问题是什么。我的代码中不断出现错误。

错误:运行时检查失败:使用的变量未初始化。: 警告 C4700: 使用了未初始化的局部变量 'b'

有人可以帮我解决这个问题吗?任何帮助将不胜感激。我正在使用 Visual Studio 作为 C 的编译器,我是它的初学者,这是一项任务。如果我输入“int b;”,我不明白为什么我会一直遇到这个问题 在程序的开头。该变量不会被初始化吗?

这是代码:

 #include <stdio.h>


  //Create a program that asks the user to enter a number until the user enters a -1 to   stop
  int main() 
  {
   int b;

      //as long as the number is not -1,  print the number on the screen
 while(b!=-1) {
 printf("Hello there! would you please enter a number?");
 scanf(" %d",&b);

 //as long as the number is not -1,  print the number on the screen
 if(b!=-1){
 printf("Thank you for your time and consideration but the following %d you entered  wasn't quite what we expected. Can you please enter another?\n",b);

    //When the user enters a -1 print the message “Have a Nice Day :)” and end the program
 }else {
 printf("Have a Nice Day :), and see you soon\n");
 }
    }
return 0;
}
4

4 回答 4

11

当您声明一个变量时,例如您有:

int b;

它没有初始化为任何值,在初始化之前它的值是未知的。

要修复此错误,请替换

int b;

int b = 0;
于 2013-10-26T04:22:57.083 回答
4

错误在这里:

int main() 
  {
   int b;

      //as long as the number is not -1,  print the number on the screen
 while(b!=-1) {

由于您还没有初始化b,它可以是任何东西。然后,您将其用作 forwhile循环的条件。这是非常危险的。

可能是系统随机为其分配值-1(这是一种罕见的可能性)..在这种情况下,您的while循环将不会被执行

初始化b为某个值

例如这样做:

int b = 0;
于 2013-10-26T04:23:01.763 回答
0

你正在做的:

int b;

然后做:

while(b!=-1) {

无需初始化b。问题正是你的警告告诉你的。

C 不会自动为您初始化局部变量,程序员必须注意这一点。int b为您的变量分配内存,但不会在其中放置值,并且它将包含分配之前该内存中的任何垃圾值。在您显式分配或另一个函数显式为其分配值之前,您的变量不会被初始化。

于 2013-10-26T04:23:23.627 回答
0
int b;

是一个变量声明。明确地,该值未初始化。编译器将发出指令让程序保留空间以在以后存储整数。

int b = 1;

这是一个带有初始化的变量声明。

int b;
while (b != -1)

这是使用未初始化的变量,但也是

int a = rand() % 3; // so 'a' can be 0, 1 and or 2.
int b;
if (a == 0)
    b = 1;
else if (a == 1)
    b = 2;
printf("b = %d\n", b);

这也是未初始化使用 b 的潜在原因。如果 'a' 是 2,我们永远不会为 b 分配默认值。

结果是您应该始终尝试在声明中指定默认值。如果确定初始化的逻辑很复杂,请考虑使用越界值,就像使用 -1 一样。

你能发现下面的错误吗?

int b = -1;
if (a == 0)
    b = 1;
else if (a == 1)
    b = 2;
else if (a > 2)
    b = 3;

if (b == -1) {
     // this is an error, handle it.
}
于 2013-10-26T04:32:19.767 回答