??? 10/21/10 07:40 Read: times Msg Score: +1 +1 Informative |
#179232 - Quite common loop design for bit operations Responding to: ???'s previous message |
Justin Fontes said:
Plus I have never seen a for loop written in this manner:
for (i = 0x01; i; i <<= 1) i is instantiated as 0x01, the for loop never compares or just makes sure i is 1? isn't supposed to be "i < 0x80" in the middle? Nothing strange with that loop. It's a one-bit-at-a-time loop, that is quite common if either writing a running light (walk the LED from D0 to D7) or when counting number of bits non-zero in a variable. If i is an 8-bit variable, it will iterate the values 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80 and break when that lonely bit gets shifted out into the void. With a 16-bit i, it will iterate 16 times instead. Remember that C don't need a comparison operator for logic expressions. It's just a question if the expression is zero or non-zero. so: char *p = NULL; int i = 0; if (!p) { printf("was NULL pointern"); } if (p) { printf("was non-NULL pointern"); } if (i) { printf("was non-zero integern"); } if (!i) { printf("was zero integern"); } That's also why you can write code like: int a = 5; int b = 10; int same = a == b; A comparison in C isn't a magic datatype "bool" - it's just a numeric expression that is zero if the comparison is false. And since there isn't a forced bool data type, if statements don't require any comparison at all - just an expression that is zero or non-zero. |