The code below ends up in a seemingly endless loop while printing some decimal numbers.
int main(){
show(0xBADECAFU);
}
void show(unsigned a){
unsigned pos=0;
for(; pos<UINT_MAX; pos++)
printf("%u", (1U<<pos) & a);
}
The code below actually shows the bits of the hex number. Why does the first program run improperly while the second does not?
int main(){
show(0xBADECAFU);
}
void show(unsigned n){
unsigned pos=31, count=1;
for(; pos!=UINT_MAX; pos--, count++){
printf("%u", n>>pos & 1U);
}
There are not
UINT_MAXbits in anunsigned int. There are, however,CHAR_BIT * sizeof(unsigned int)bits.Consider your second case, where you loop until
posequalsUINT_MAX. This will properly* print out 32 bits ofunsigned, assuming underflow goes to~0andsizeof(unsigned)is at least 4.Your second example could be improved slightly:
* Your code which “prints” the bits was odd, and in my example I’ve fixed it up.