Path: csiph.com!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:59:00 -0800 Organization: None to speak of Lines: 60 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+xktq2u9OZMtlk9itUn/5+" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/23.1 (gnu/linux) Cancel-Lock: sha1:TJJvKAXpT3mgYpoazatl3289v5k= sha1:/aCEBSZE9PCjshrmNPg90b1ovNA= Xref: csiph.com comp.lang.c:105195 BartC writes: > On 28/02/2017 23:33, Lowell Gilbert wrote: >> 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. From reading the standard, >> my expectation was that the multiplication would convert the signed >> operand to unsigned, based on this bit of the standard: >> >> Otherwise, if the operand that has unsigned integer type has rank >> greater or equal to the rank of the type of the other operand, >> then the operand with signed integer type is converted to the >> type of the operand with unsigned integer type. >> >> They've got the same rank, right? >> >> What am I missing? [It must be something, because I don't even get >> warnings on any of several compilers, with messages cranked up high.] > > Try: > > printf("%u\n", c); No, c is an int. But do try: printf("%llu\n", a * b); That will show you the actual value that's converted to int before being stored in c. On my system, with the obvious changes to the OP's program, I get: a * b = 18446744073709511616 c = -40000 or, when I compile in 32-bit mode: a * b = 4294927296 c = -40000 (Again, the conversion has undefined behavior, but these results is likely to be typical.) -- 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"