C's comparison's wrong with hierarchy promotion -
#include <stdio.h> int main() { unsigned int x=1; char y=-1; if (x>y) { printf("x>y"); } else if(x==y) printf("x=y"); else printf("x<y"); return 0; }
when run code above, last else's printf, embarrassing, because x 1 , y -1.
i think there's comparison, 'x>y', hierarchical promotion, cause when change x's type 'int', not 'unsigned int', right. problem interesting.. answer/thinking/suggestion welcome.
it correct, according standard.
firstly, implementation defined whether char
signed
or unsigned
.
if char
unsigned
, initialisation use modulo arithmetic, initialising -1
initialise maximum value of unsigned char
- guaranteed greater 1. comparison convert char
unsigned
(which doesn't change value) before doing comparison.
if char
signed
, comparison convert char
value -1
of type unsigned
(since x of type unsigned
). conversion, again, uses modulo arithmetic, except respect unsigned
type (so -1
convert maximum value unsigned
can represent). results in value exceeds 1.
in practice, turning warning levels on compiler trigger warnings on sort of thing. idea in practice since code arguably behaves in manner less intuitive.
Comments
Post a Comment