我刚刚尝试给a
、b
和d
提供相同的值,每次运行代码时都会生成一个随机值。
#include <stdio.h>
int main()
{
int a = 4; //type declaration instructions
int b = 999, c, d;
a = b = d;
printf("The value of a and b is %d and %d n", a, b);
return 999;
}
让我们逐行进行。
-
声明一个整数
a
,并将其初始化为值4
int a = 4;
-
声明3个整数
b
、c
、d
,并将b
初始化为999
。由于c
和d
未被初始化,因此它们具有垃圾值(先前存储在存储器块中的值,该存储器块现在已被分配给c
和d
(。int b = 999,c,d;
-
故障代码。
d
中的垃圾值设置为a
和b
a=b=d;
校正-初始化d
,或者不将a
和b
设置为d
。
#include <stdio.h>
int main()
{
int a = 4; //type decleration instructions
int b = 999,c,d = 1000; // initialise d
a=b=d;
printf("The value of a and b is %d and %d n",a,b);
return 999;
}
在每次执行该程序时获得随机值的原因是,如果没有定义变量,C会分配Garbage值(即任何随机数(。
但是这个程序完全依赖于编译器,因为如果我们不定义的话,很少有编译器会默认将值分配给0
因此,这个程序的输出可能会因您使用的C编译器而异。例如,如果您正在使用某个在线C编译器,那么它很可能会给出0作为输出,而有些编译器可能会给出随机值(Garbage值(作为输出。
You declared variable c and d without assigning its values so random values are assigned to d .
hence assignment operator works right to left so
a=b=d
first:
b=d works so random value of d goes in b
and then :
a=b works so that random value goes in a
so try using=>
d=b=a
you will get:
a=4
b=4
d=4