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

变量是否在未初始化的情况下使用?C语言,c,C,我不太明白我的问题是什么。我的代码中不断出现错误 错误:运行时检查失败:未初始化就使用了变量。 :警告C4700:使用了未初始化的局部变量“b” 有人能帮我解决这个问题吗?任何帮助都将不胜感激。我正在使用visual studio作为C的编译器,我是C的初学者,这是一个作业之一。如果我输入int b,我不明白为什么我会一直遇到这个问题;在节目开始的时候。那个变量不会被初始化吗 代码如下: #include <stdio.h> //Create a program that

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

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


有人能帮我解决这个问题吗?任何帮助都将不胜感激。我正在使用visual studio作为C的编译器,我是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;
}

声明变量时,例如:

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

若要修复此错误,请替换

int b;

错误如下:

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不会自动为您初始化局部变量,程序员必须注意这一点。INTB为变量分配内存,但不在其中放入值,它将包含分配前内存中的任何垃圾值。只有在您显式赋值或另一个函数显式赋值之前,才会初始化变量

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

实际上,b的值可以是-1或任何其他数字。不,C不会自动为您初始化局部变量,程序员必须处理这个问题。这个变量不会被初始化吗?无论你用什么书来学习C,如果它说声明一个变量会自动初始化它,那么它都不是很好。为什么不能在编译时而不是运行时检测到它呢?
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.
}