C:在子程序修复程序分配给本地变量,为什么呢? [英] C: assigning to local variable in subroutine fixes program, why?
问题描述
double earthmaxangle(double time, int arrsize, SpiceInt *planets) {
double max=0, sep;
int i,j;
for (i=0; i<arrsize; i++) {
for (j=i+1; j<arrsize; j++) {
sep = earthangle(time, planets[i], planets[j]);
if (sep>max) {max=sep;}
}
}
return max;
}
在code以上编译和正常工作。但是,如果我删除 = 0
最大后,的gcc -Wall -O2
给我这样的警告:
The code above compiles and works correctly. However, if I remove the =0
after max, gcc -Wall -O2
gives me this warning:
bc-planet-conjuncts.c: In function 'earthmaxangle':
bc-planet-conjuncts.c:42: warning: 'max' may be used uninitialized in this function
和,更重要的是,该程序的功能的不的正常工作。
and, more importantly, the program does not work correctly.
为什么呢?而我为什么不得到未初始化警告的变量九月
(甚至 I
或Ĵ
为此事)?
Why? And why don't I get the "uninitialized" warning for the variable sep
(or even i
or j
for that matter)?
推荐答案
您没有得到警告月
, I
,Ĵ
,因为这些变量在使用之前给出一个值:
You don't get warnings for sep
, i
, j
because those variables are given a value before being used:
for (i=0; ...
这行初始化 I
。
for (j=i+1; ...
这行初始化Ĵ
。
sep = earthangle(time, planets[i], planets[j]);
这行初始化月
。
然而,没有什么是执行,让最大
这code前值:
However, there's nothing that gives max
a value before this code is executed:
if (sep>max)
所以在这一点上,从读值最大
是不确定的;因此警告。
So at this point, the value read from max
is indeterminate; hence the warning.
这篇关于C:在子程序修复程序分配给本地变量,为什么呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!