Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C/C++ casting different with function versus expression?

Tags:

c++

c

#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 (on both GCC and Clang):

127
150

Why am I getting two different numbers?

like image 381
Alex Henrie Avatar asked Dec 11 '22 14:12

Alex Henrie


1 Answers

The real answer (150) exceeds the range of a char (on a normal system) if it's signed. This conversion invokes undefined behaviour; the compiler is free to do whatever it likes.

From the C99 standard, 6.3.1.4:

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.

like image 187
Oliver Charlesworth Avatar answered Dec 14 '22 03:12

Oliver Charlesworth