与属性warn_unused_result声明 [英] Declared with attribute warn_unused_result

查看:824
本文介绍了与属性warn_unused_result声明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include<stdio.h>

int main() {
    int t;
    scanf("%d",&t);
    printf("%d",t);
    return 0;
}

我编译使用Ideone.com上述C code和下面的警告弹出。

I compiled the above c code using Ideone.com and the following warning popped up.

prog.c中:在函数'主':结果
  prog.c中:5:警告:忽略返回值
  scanf函数,带属性warn_unused_result声明

prog.c: In function ‘main’:
prog.c:5: warning: ignoring return value of ‘scanf’, declared with attribute warn_unused_result

能有人帮我这个?难道我愚蠢?

Can some one help me about this? did I do something idiotic?

推荐答案

不,你没做什么愚蠢的。你的libc的作家已经决定, scanf函数的返回值不应在多数情况下可以忽略,所以他们给了它告诉编译器给你一个警告,一个属性。

no, you didn't do anything idiotic. The writer's of your libc have decided that the return value of scanf should not be ignored in most cases, so they have given it an attribute telling the compiler to give you a warning.

如果是真正不需要返回值,那么你的罚款。然而,它通常是最好的检查,以确保你真正成功读取你认为你做了。

If the return value is truly not needed, then you are fine. However, it is usually best to check it to make sure you actually successfully read what you think you did.

在你的情况下,code可以写成这样避免了警告(和一些输入错误):

In your case, the code could be written like this to avoid the warning (and some input errors):

#include <stdio.h>

int main() {
    int t;
    if (scanf("%d", &t) == 1) {
        printf("%d", t);
    } else {
        printf("failed to read integer.\n");
    }
    return 0;
}

这篇关于与属性warn_unused_result声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆