变量在没有初始化的情况下使用? C语言

我无法弄清楚我的问题在这里。 我的代码中一直出错。

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

有人可以帮我解决这个问题吗? 任何帮助将不胜感激。我使用visual studio作为C的编译器,我是它的初学者,这是一个任务。 如果输入“int b”,我不明白为什么我会继续这个问题。 在该计划的开头。 这个变量不会被初始化吗?

这是代码:

#include  //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; } 

声明变量时,例如:

 int b; 

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

要修复此错误,请替换

 int b; 

 int b = 0; 

错误在这里:

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

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

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

初始化b到某个值

例如,这样做:

 int b = 0; 

你在做:

 int b; 

然后做:

 while(b!=-1) { 

没有初始化b 。 问题正是你的警告告诉你的问题。

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

 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指定默认值。

Upshot是你应该总是尝试使用声明指定默认值。 如果确定初始化的逻辑很复杂,请考虑使用越界值,因为您使用的是-1。

你能发现以下的bug吗?

 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. }