Hacker News new | past | comments | ask | show | jobs | submit login

What does that loop even do?



  > What does that loop even do?

  for (i=0; i<8 && (c|32)=="infinity"[i]; i++)
    if (i<7) c = shgetc(f);
It's a pattern matching loop. The 'c' variable is a character which is read from FILE * f. In this case, it's attempting to match the string "infinity" which has a length of 8. With ASCII, uppercase letters start from hex value 0x41 for the letter 'A'. Lowercase letters start from hex value 0x61 for the letter 'a'. Thus the difference between lowercase and uppercase is 0x20 which is 32 decimal or 100000 in binary. Thus, if you or the value of 'c' with 32 (0x20 or 00010000), you're setting the 2^5 bit of the character which converts uppercase to lowercase and leaves lowercase unchanged since all lowercase characters already have that bit set.

I'm sure you can figure out the rest. As long as the character matches the corresponding index position in the character array "infinity", the for loop keeps matching characters. Eventually, a successful match results in a return value of sign * INFINITY from the function.


Woe to the developer trying to parse 0x13a0ce!


The whole function is trying to parse a float value, that loop is looking for the string "Infinity".

c|32 will do a bitwise downcase of an ascii character so, "INFINITY", "infinity", "INfinITy" will all be accepted. In any of those cases i == 8 at the end of the loop and is still in scope, so the following if statement will ultimately return + or - Infinity.


ASCII case-insensitive comparison of up to 8 characters from a stream with "infinity".




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: