Is C / C ++ different from a function compared to an expression?

#include <stdio.h> double metersToFeet(double meters) { return meters / 0.3048; } int main() { printf("%u\n", (unsigned char)(char)(45.72 / 0.3048)); printf("%u\n", (unsigned char)(char)metersToFeet(45.72)); return 0; } 

This program outputs (both on GCC and Clang):

 127 150 

Why am I getting two different numbers?

+4
source share
2 answers

The real answer (150) exceeds the range of a char (in a normal system) if it is signed. This conversion causes undefined behavior ; the compiler can do whatever he likes.

From standard C99, 6.3.1.4:

When the final value of the real floating type is converted to an integer type other than _Bool, the fractional part is discarded (i.e. the value is truncated to zero). If the value of the integral part cannot be represented as an integer type, the behavior is undefined.

+8
source

45.72 / 0.3048 150 .

The char type on your platform is apparently 8, but a signed type. 150 is out of this range. This means that the behavior is undefined. The rest follows.

For example, I get 127,127 in GCC through ideone.com and 150,150 in MSVC. You got 127 150 , which is funny, but not surprising.

+5
source

Source: https://habr.com/ru/post/1484538/


All Articles