Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
951 views
in Technique[技术] by (71.8m points)

c - Type casting: double to char: multiple questions

Consider this code:

#include <stdio.h>

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

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

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

Results:

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

* latest version

Questions:

  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?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When CHAR_MAX == 127, (char)128.0 is undefined behavior (UB).

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...