如何明智地解释此编译器警告? [英] How to wisely interpret this compiler warning?

查看:112
本文介绍了如何明智地解释此编译器警告?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我执行此问题的代码时,我得到了以下警告:

When I executed the code of this question, I got this warning:

warning: format '%d' expects argument of type 'int', but argument 2 has type 'long int' [-Wformat=]
printf("P-Q: %d, P: %d, Q: %d", (p - q), p, q);
             ~^                 ~~~~~~~
             %ld

作为反射修复,我使用了%ld来打印两个指针的减法.编译器同意了.

As a reflex fix, I used %ld to print the subtraction of two pointers. And the compiler agreed.

幸运的是,我看到另一个用户的评论,其中提到应该使用%td,因为减法的结果类型是ptrdiff_t.此 answer 确认了这一主张.

Fortunately, I saw a comment from another user mentioning that %td should be used, since the result type of the subtraction is ptrdiff_t. This answer confirms this claim.

现在来自GCC的头文件 stddef.h ,在这种情况下,我可以看到这些类型是等效的:

Now from GCC's header file of stddef.h, I can see that these types are equivalent in this case:

typedef __PTRDIFF_TYPE__ ptrdiff_t;
#define __PTRDIFF_TYPE__ long int

但是,我只是建议使用%ld而不是%td对OP进行错误的(或多或少)修复.

However, I was just going to suggest a wrong (more or less) fix to the OP, with %ld, instead of %td.

有没有办法让我理解仅编译器警告是不够的?或者,也许是明智地解释了警告本身,而不仅仅是做出了反应.

Is there a way I could have understood that the compiler warning alone was not enough? Or maybe to wisely have interpreted the warning itself, and not just react.

推荐答案

我认为您看不出来.这取决于编译器编写者的意图/谨慎/聪明.

I don't think you can tell. It depends on the intent/caution/smartness of the compiler writer.

也许他决定在需要%td的地方总是支持%ld,或者他只是不知道/无法/不愿意给出更详细/正确的信息.如有疑问,您的最后选择就是标准.

Maybe he decided he would always support %ld where %td is expected, or maybe he was just unaware/unable/unwilling to give a more detailed/proper message. In case of doubt, your last resort is the standard.

这似乎不是可移植的结构,对于正统",您应该同时支持两种格式说明符.

This doesn't seem to be a portable construct and for "orthodoxy" you should support both format specifiers.

这篇关于如何明智地解释此编译器警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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