Signed mod unsigned



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

--
Wo hattest Du das Beben nochmal GENAU vorhergesagt?
Zumindest nicht öffentlich!
Ah, der neueste und bis heute genialste Streich unsere großen
Kosmologen: Die Geheim-Vorhersage.
- Karl Kaos über Rüdiger Thomas in dsa <hidbv3$om2$1@xxxxxxxxxxxxxxxxx>
.



Relevant Pages

  • Re: Question regarding sequence point
    ... The while I compiled the code using gcc -Wall I got the following ... ub.c:5: warning: operation on `i' may be undefined ... Of course, to compile ...
    (comp.lang.c)
  • [git patches 2/2] warnings: use uninitialized_var()
    ... used uninitialized" warning fixes, in misc-2.6.git#gccbug. ... 'uninit-var', you will receive BOTH 'uninit-var' and 'warnings' ... struct cyclades_port *info; ... unsigned int cur_frag, entry; ...
    (Linux-Kernel)
  • Re: shame on MISRA
    ... extern unsigned char variable1; ... extern unsigned int variable2; ... the warning for that in the MISRA rules turned off since I'm using ...
    (comp.arch.embedded)
  • Re: If you could change the C or C++ or Java syntax, what would you like different?
    ... GCC does emit a warning in many cases. ... on my system size_t is a typedef for unsigned int. ... Certainly compilers *can* use typedef information in warnings. ...
    (comp.lang.c)
  • Re: I Hate Warnings! This One Has Me.
    ... typedef unsigned int _w64 size_t; ... which means it will go to 64 bits in 64-bit systems, and so the warning ... > In class TProductData: ... > Where the dickens did "unsigned int" come from, ...
    (microsoft.public.vc.language)