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

时间:2013-10-26 04:20:47

标签: c

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

错误:运行时检查失败:未初始化时使用的变量。 :警告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 个答案:

答案 0 :(得分:9)

声明变量时,例如:

int b;

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

要解决此错误,请替换

int b;

使用

int b = 0;

答案 1 :(得分:4)

错误在这里:

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;

答案 2 :(得分:0)

你在做:

int b;

然后做:

while(b!=-1) {

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

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

答案 3 :(得分: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。

指定默认值

Upshot是您应该总是尝试使用声明指定默认值。如果确定初始化的逻辑很复杂,请考虑使用越界值,因为使用-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.
}