Path: csiph.com!news.swapon.de!eternal-september.org!feeder.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail From: Keith Thompson Newsgroups: comp.lang.c Subject: Re: "usual arithmetic conversions": please explain something... Date: Tue, 28 Feb 2017 16:03:53 -0800 Organization: None to speak of Lines: 36 Message-ID: References: <448topoppn.fsf@be-well.ilk.org> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Injection-Info: mx02.eternal-september.org; posting-host="40f2111bd31821bfebd41309549fe646"; logging-data="19679"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1+Tda+//Wa0WB9Hq5fN9DKl" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/23.1 (gnu/linux) Cancel-Lock: sha1:h0Q+k4NRWE7uGHoiGcQPFeSCXNE= sha1:4zBeZmfL2VjgYNyD+kBwPSyEA00= Xref: csiph.com comp.lang.c:105190 Lowell Gilbert writes: > Given the following program: > > #include > > int main (void) > { > unsigned long a = 4000; > signed long b = -10; > int c; > > c = a * b; > printf("%d\n", c); > > return 0; > } > > I am surprised that I get a negative answer. [...] Multiplying an unsigned long by a signed long converts the signed long operand to unsigned long. Converting -10 to unsigned long yields ULONG_MAX-9, which when multiplied by 4000 yields some large number that wraps around in the usual manner. On my system, with 64-bit long, the result is 18446744073709511616; with 32-bit long, it's 4294927296. The assignment converts that value from unsigned long to (signed) int. The behavior is undefined (assuming that value exceeds INT_MAX, which it almost certainly does, but *typically* it will discard the high-order bits yielding -40000. -- Keith Thompson (The_Other_Keith) kst-u@mib.org Working, but not speaking, for JetHead Development, Inc. "We must do something. This is something. Therefore, we must do this." -- Antony Jay and Jonathan Lynn, "Yes Minister"