Signed mod unsigned
- From: Johannes Bauer <dfnsonfsduifb@xxxxxx>
- Date: Wed, 06 Jun 2012 15:55:07 +0200
Hi group,
today I ran into something I honestly did not expect. Consider this snippet:
#include <stdio.h>
int main() {
int i1, i2;
unsigned int u2;
i1 = -1;
i2 = 30;
u2 = 30;
printf("%d\n", i1 % i2);
printf("%d\n", i1 % u2);
return 0;
}
I expected to find the output "-1 / -1". Instead the result I got was
"-1 / 15". Apparently when getting the remainder of a signed by a
unsigned int, the signed is silently promoted to unsigned in twos
complement and then the operation is performed, i.e.
0xffffffff % 30 == 15
I would have expected at least a warning since I find this highly
unintuitive -- my expectation would be that the unsigned becomes a
(truncated) signed and a warning. Instead gcc does not emit a warning
(-Wall -Wextra) and silently performs above operation.
Is this really in accordance with the C standard or is gcc doing
something weird here?
Best regards,
Joe
--
Ah, der neueste und bis heute genialste Streich unsere großenWo hattest Du das Beben nochmal GENAU vorhergesagt?Zumindest nicht öffentlich!
Kosmologen: Die Geheim-Vorhersage.
- Karl Kaos über Rüdiger Thomas in dsa <hidbv3$om2$1@xxxxxxxxxxxxxxxxx>
.
- Follow-Ups:
- Re: Signed mod unsigned
- From: Edward Rutherford
- Re: Signed mod unsigned
- From: gwowen
- Re: Signed mod unsigned
- From: James Kuyper
- Re: Signed mod unsigned
- Prev by Date: Re: Why was there a GOTO? (was Re: GOTOs discovered in "real world" program!)
- Next by Date: Re: Why was there a GOTO? (was Re: GOTOs discovered in "real world" program!)
- Previous by thread: Why no warning?
- Next by thread: Re: Signed mod unsigned
- Index(es):
Relevant Pages
|