本文介绍了为什么不的gcc -Wformat警告printf的%D于一个unsigned int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的程序是未定义行为:

 的#include<&stdio.h中GT;INT主要(无效)
{
    unsigned int类型X = -100; //这是罚款,成为UINT_MAX - 100
    的printf(%d个\\ N,X); //这是不确定的行为。
    返回0;
}

However, gcc -Wformat (which is included with -Wall) will not complain about the above program, why? Is this a bug, or a deliberate omission?

From the gcc manpage:

-Wformat

Check calls to "printf" and "scanf", etc., to make sure that the arguments supplied have types appropriate to the format string specified, and that the conversions specified in the format string make sense

解决方案

My best guess is that the warning is skipped because the UB is arguably invoked by the value and not merely by the type. va_arg allows the signedness to mismatch as long as the value is representable in both the signed and unsigned type. However, printf and friends are not specified in terms of va_arg and the standard states that any type mismatch results in UB, but this is probably a bug in the standard. Otherwise, printf("%x",1); would invoke UB. See my question on the topic:

Does printf("%x",1) invoke undefined behavior?

这篇关于为什么不的gcc -Wformat警告printf的%D于一个unsigned int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 18:32