Path: utzoo!censor!geac!torsqnt!news-server.csri.toronto.edu!mailrus!umich!samsung!dali.cs.montana.edu!uakari.primate.wisc.edu!aplcen!haven!adm!smoke!gwyn From: gwyn@smoke.BRL.MIL (Doug Gwyn) Newsgroups: comp.std.c Subject: Re: Is a CAST (double) -> (int) guaranteed to truncate ? Message-ID: <13334@smoke.BRL.MIL> Date: 10 Jul 90 02:47:42 GMT References: <1431@tub.UUCP> Organization: U.S. Army Ballistic Research Laboratory, APG, MD. Lines: 24 In article <1431@tub.UUCP> heim@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.