J
Johannes Bauer
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
--
Kosmologen: Die Geheim-Vorhersage.
- Karl Kaos über Rüdiger Thomas in dsa <[email protected]>
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ßenZumindest nicht öffentlich!
Kosmologen: Die Geheim-Vorhersage.
- Karl Kaos über Rüdiger Thomas in dsa <[email protected]>