2013-06-24 28 views
5

當我編譯如下程序: g++ -O2 -s -static 2.cpp它給了我警告ignoring return value of ‘int scanf(const char*, ...)’, declared with attribute warn_unused_result [-Wunused-result]
但是,當我從複製語句中刪除-02時,不顯示警告。忽略'int scanf(const char *,...)'的返回值,用屬性warn_unused_result [-Wunused-result]聲明?

2.cpp程序:

#include<stdio.h> 
int main() 
{ 
    int a,b; 
    scanf("%d%d",&a,&b); 
    printf("%d\n",a+b); 
    return 0; 
} 


這是什麼警告的意思,什麼是-O2意思?

回答

7

這意味着你不檢查scanf的返回值。

它可能很好地返回1(僅設置a)或0(a和b都不設置)。

編譯時未顯示優化時未顯示的原因是,除非啓用優化,否則需要分析才能看到此內容。 -O2啓用優化 - http://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html

簡單地檢查返回值將刪除警告,使程序的行爲在可預測的方式,如果沒有收到兩個數字:

if(scanf("%d%d", &a, &b) != 2) 
{ 
    // do something, like.. 
    fprintf(stderr, "Expected at least two numbers as input\n"); 
    exit(1); 
} 
+0

讓我怎麼消除這種警告,因爲直到日期,所有我寫我從來沒有檢查scanf函數的返回值的C程序!還有什麼是這個優化參數可以拋出一些光? –

+0

@perh這是一個很好的理由嗎? – Antonio

+0

好吧,不檢查意味着如果任何一個變量沒有被sscanf設置(使用未初始化的值),程序將返回錯誤的值。這只是一個警告,不是一個錯誤。至於由於缺乏編譯器執行的分析而未使用(至少)-O時未顯示 - 這就是它的原因。 – perh

0

我通過做一個匹配的if語句照顧的警告參數個數:

#include <iostream> 
#include <cstdio> 
using namespace std; 

int main() { 
    int i; 
    long l; 
    long long ll; 
    char ch; 
    float f; 
    double d; 

    //6 arguments expected 
    if(scanf("%d %ld %lld %c %f %lf", &i, &l, &ll, &ch, &f, &d) == 6) 
    { 
     printf("%d\n", i); 
     printf("%ld\n", l); 
     printf("%lld\n", ll); 
     printf("%c\n", ch); 
     printf("%f\n", f); 
     printf("%lf\n", d); 
    } 
    return 0; 
}