这是否未定义行为? [英] Does this invoke undefined behaviour?

查看:104
本文介绍了这是否未定义行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑下面的C程序:

#include <stdio.h>

int main(){
    int a =-1;
    unsigned b=-1;
    if(a==b)
        printf("%d %d",a,b);
    else
       printf("Unequal");
    return 0;
 }

在该行的printf(%D,A,B); %D是用来打印无符号类型。这是否未定义行为,为什么?

In the line printf("%d %d",a,b);, "%d" is used to print an unsigned type. Does this invoke undefined behavior and why?

推荐答案

虽然明确允许使用的va_arg 宏从&LT; stdarg头文件.H&GT; 来检索被作为传递参数的无符号 INT ( 7.15.1.1/2),fprintf中的文档(7.19.6.1/9),这也适用于的printf 中,它明确规定,如果任何参数是不正确的类型格式说明 - 一个未修改%d个,即 INT - 则行为没有定义

Although you are explicitly allowed to use the va_arg macro from <stdarg.h> to retrieve a parameter that was passed as an unsigned as an int (7.15.1.1/2), in the documentation for fprintf (7.19.6.1/9) which also applies to printf, it explicitly states that if any argument is not the correct type for the format specifier - for an unmodified %d, that is int - then the behaviour is not defined.

作为评论@bdonlan笔记,如果的值(在这种情况下, 2 ^ N - 1 对于一些 N )未在 INT 那么这将是的未定义行为重新presentable 的尝试访问该值作为 INT 使用的va_arg 在任何情况下。这只会在平台上工作的地方重新presentation一个无符号使用至少一个填充位,其中相应的 INT 重新presentation有一个符号位。

As @bdonlan notes in a comment, if the value of b (in this case 2^N - 1 for some N) is not representable in an int then it would be undefined behavior to attempt to access the value as an int using va_arg in any case. This would only work on platforms where the representation of an unsigned used at least one padding bit where the corresponding int representation had a sign bit.

即使在情况下的值(无符号)-1 可重新在psented $ P $ INT ,我还是看这是在技术上的未定义行为的。作为实施的一部分,它似乎被允许用于执行使用内置的魔法,而不是 va_args 来访问参数的printf 如果您通过什么作为无符号其中的 INT 是必需的,那么你在技术上违反了合约的printf

Even in the case where the value of (unsigned)-1 can be represented in an int, I still read this as being technically undefined behavior. As part of the implementation, it would seem to be allowed for an implementation to use built in magic instead of va_args to access the parameters to printf and if you pass something as an unsigned where an int is required then you have technically violated the contract for printf.

这篇关于这是否未定义行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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