类型转换:双精度字符:多个问题 [英] Type casting: double to char: multiple questions

查看:53
本文介绍了类型转换:双精度字符:多个问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

#include <stdio.h>

int main(void) 
{
    /* TEST 1 */
    double d = 128;
    char ch = (char)d;
    printf("%d\n", ch);

    /* TEST 2 */
    printf("%d\n", (char)128.0);

    /* TEST 3 */
    char ch1 = (char)128.0;
    printf("%d\n", ch1);
    return 0;
}

结果:

        gcc*  clang*  cl*
TEST 1  -128  -128    -128
TEST 2  127   0       -128
TEST 3  127   -2      -128

* latest version

问题:

  1. 为什么测试之间的结果有所不同(不包括 cl )?
  2. 为什么编译器之间的结果不同( TEST 1 除外)?
  3. 对于UB/IB,UB/IB到底在哪里?标准怎么说?
  4. [额外问题]为什么 clang 表现出如此不同的行为?这些 0 -2 来自何处?
  1. Why the results differ between tests (excluding cl)?
  2. Why the results differ between compilers (excluding TEST 1)?
  3. In case of UB/IB, where is the UB/IB exactly? What the standard says?
  4. [Extra question] Why clang shows so different behavior? Where these 0 and -2 come from?

推荐答案

CHAR_MAX == 127 时,(char)128.0 未定义的行为(UB).

当实数浮点型的有限值转换为除 _Bool 以外的整数类型时,小数部分将被丢弃(即,该值将被截断为零).如果整数部分的值不能用整数类型表示,则行为是不确定的.C17dr§6.3.1.4 1

When a finite value of real floating type is converted to an integer type other than _Bool, the fractional part is discarded (i.e., the value is truncated toward zero). If the value of the integral part cannot be represented by the integer type, the behavior is undefined. C17dr § 6.3.1.4 1

这不是UB,原因是整数溢出.由于转换规则,它是UB.

This is not UB due to integer overflow. It is UB due to conversion rules.

这篇关于类型转换:双精度字符:多个问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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