Is a CAST (double) -> (int) guaranteed to truncate ?
Doug Gwyn
gwyn at smoke.BRL.MIL
Tue Jul 10 12:47:42 AEST 1990
In article <1431 at tub.UUCP> heim at tub.UUCP (Heiner Marxen) writes:
>It occurs to me that most C programmers assume that the cast operator
>from double to int truncates the value (rounds towards 0), i.e. the above
>program is expected to print " -1 -1 1 1". But, is this behaviour
>guaranteed/enforced by the definition of C?
The C standard requires that conversion of a floating type to an integer
type discard the fractional part, i.e. truncate toward zero. Pre-ANSI C
implementations differ in their treatment of such cases. I even found
one compiler recently that rounded on
double d = 0.9; long i = d;
but truncated on
double d = 0.9; long i = (long)d;
>A similar question applies to integer division. Consider the C program
> main() { printf("%d %d\n", 4/3, 5/3); }
>Is "1 1" its only legal output, or may it print "1 2"?
Integer division of positive operands has always been defined in C as
truncating toward zero (discarding remainder). Behavior with negative
operands has deliberately been allowed to vary, in order to permit the
simple use of a hardware-divide instruction in the generated code.
The C standard DOES require that i/j and i%j obey a certain definite
algebraic relationship, though: (i/j)*j+i%j==i.
More information about the Comp.std.c
mailing list