In step 33, this version of the getCursorPosition function is presented:
int getCursorPosition(int *rows, int *cols) { char buf[32]; unsigned int i = 0; if (write(STDOUT_FILENO, "\x1b[6n", 4) != 4) return -1; while (i < sizeof(buf) - 1) { if (read(STDIN_FILENO, &buf[i], 1) != 1) break; if (buf[i] == 'R') break; i++; } buf[i] = '\0'; if (buf[0] != '\x1b' || buf[1] != '[') return -1; if (sscanf(&buf[2], "%d;%d", rows, cols) != 2) return -1; return 0; }
This is more of a minor stylistic issue compared to the previous stuff I've commented on, but I prefer to write loops like this using for:
int getCursorPosition(int *rows, int *cols) { if (write(STDOUT_FILENO, "\x1b[6n", 4) != 4) return -1; unsigned int i = 0; char buf[32]; for (i = 0; i < sizeof(buf) - 1; i++) { if (read(STDIN_FILENO, &buf[i], 1) != 1) break; if (buf[i] == 'R') break; } buf[i] = '\0'; if (buf[0] != '\x1b' || buf[1] != '[') return -1; if (sscanf(&buf[2], "%d;%d", rows, cols) != 2) return -1; return 0; }
In this version, the initialization of i = 0 is contained within the loop, and the loop structure (IMO, anyway) is clearer. Whenever a loop is iterating on an integer variable with a hard upper bound, I just feel like a for loop makes it clearer what's happening. Also, since this project explicitly uses C99, there's no reason declare variables until they're actually needed.
No comments:
Post a Comment