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: Wed, 01 Mar 2017 09:43:22 -0800 Organization: None to speak of Lines: 67 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="21586"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX18IsJkiCFYbnKQQSWFy1w3/" User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/23.1 (gnu/linux) Cancel-Lock: sha1:hDrtmgygCsELZKcleuS2cp0BFpA= sha1:Ep4zZnVZd1hi58SGeWA5DuvCGOA= Xref: csiph.com comp.lang.c:105287 BartC writes: > On 01/03/2017 16:25, Keith Thompson wrote: >> BartC writes: >>> On 01/03/2017 00:59, Keith Thompson wrote: >>>> BartC writes: >> [...] >>>>> Try: >>>>> >>>>> printf("%u\n", c); >>>> >>>> No, c is an int. >>>> >>>> But do try: >>>> >>>> printf("%llu\n", a * b); >> >> My mistake, I meant "%lu\n", not "%llu\n". >> >>> It doesn't make much difference. Trying this (on a machine where long is >>> 32 bits): >> >> Sure, if you use an incorrect format you can sometimes learn >> something about the value being passed to printf, or its >> representation -- but what's the point? c is of type int, and >> happens to have a negative value; printing it as if it were an >> unsigned int means you're lying to the compiler, and the behavior >> is undefined. Printing the value of a * b shows you the actual >> value that was converted to int. >> >> I showed how to print the actual values with their correct types. > > I showed how to convert the result of a signed/signed, > unsigned/unsigned, signed/unsigned or unsigned/signed to a float, which > is a better idea. I showed how to print the actual values without converting them. Converting to floating-point is not helpful, and introduces irrelevant issues. > Otherwise you're going always going to be forcing such a result into > either a signed or unsigned int, so you will not know what it actually was. No, the result is an unsigned long, which is what it actually is. > In fact, the true result of the OP's calculation was 4294927296, with > the operands being 4000 and 4294967286 (the -10). Which calculation? There were several. unsigned long a = 4000; signed long b = -10; int c; c = a * b; The result of the multiplication was a number of type unsigned long. The result of the implicit conversion was a different number of type int. The OP's original code combined those two operations; mine split them up so you could see the intermediate result. [...] -- 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"