warning: ‘x’ may be used uninitialized in this function
警告:未初期化変数かも
[-Wmaybe-uninitialized]
■1.スパゲティコード
この警告が出るのは
gccコンパイラが変数の初期化をどこで行っているか
ソースコードを追いきれないからです。
gccコンパイラも追いきれないソースコードなので
普通のプログラマもソースコードを追うのは一苦労です。
このようなソースコードを
スパゲティコード(こんがらがったコード)と言います。
■2.if文で設定条件と参照条件が違う時
int f1(int x,int y)
{
int type1;
if(x == 1234){
type1 = 1234 ;//設定
}
if(y == 5678){
return type1;//参照
}
return 0;
}
変数設定条件と
変数参照条件が違うので
変数参照時に値が設定されているかよくわからない。
■3.for文で最大値変数が0の時
int f2(int max)
{
int type2 ;
for(int i = 0 ; i < max;i++) { //max が0の時回らないので type2 はごみ
type2 = i ;
}
return type2 ;
}
for文第2式の最大値が変数の時、最大値が0かもしれない。
ループが回らないとゴミのまま。
■4.for文でif文が一度も成立しない時
int f3(int x,int ary[])
{
int type3 ;
for(int i = 0 ; i < 10;i++) {
if(ary[i] == x) {// if文が一度も成立しない時 type3 はごみ
type3 = i ;
}
}
return type3 ;
}
for文内のif文が一度も成立しないとゴミのまま。
■5.else if の最後にelse が無い時
int f4(int x)
{
int type4 ;
if(x > 0) {
type4 = 1;
} else if(x < 0) {
type4 = -1;
} // else if 多分岐通過時 type4はゴミ
return type4;
}
else if 多分岐に漏れがあるとゴミのまま(x==0の時)
■6.switch 最後にdefaultが無い時
typedef enum{a,b,c} abc_t;
int f5(abc_t x)
{
int type5;
switch(x) {
case a: type5 = 0; break;
case b: type5 = 1; break;
case c: type5 = 2; break;
}
return type5;
}
switch多分岐に漏れがあるとゴミのまま(defaultの時)
参考:
EXP33-C. 初期化されていないメモリからの読み込みを行わない
https://www.jpcert.or.jp/sc-rules/c-exp33-c.html
出力用引数よりも戻り値を使用してください。
https://ttsuki.github.io/styleguide/cppguide.ja.html#Output_Parameters
C-FAQ1.30: 自動の寿命を持つ変数の中身は、明示的に初期化しない限りゴミである
http://www.kouno.jp/home/c_faq/c1.html#30
■7.アンケート