4 ms·
"The proper way"? Not only is it less familiar than the usual "i = 0; i < n; i++" idiom, requiring the reader to examine exactly what it's doing, but now i goes
by Rangi42 13y ago
"The proper way"? Not only is it less familiar than the usual "i = 0; i < n; i++" idiom, requiring the reader to examine exactly what it's doing, but now i goes from n to 1 instead of 0 to n-1. What's so bad about caching the strlen result in a variable beforehand?
- tedunangst 13y agoYou have read his loop wrong. It has the same bounds.
- nitrogen 13y agoi goes from n-1 to 0 in the example because for loops execute the condition before the first iteration.
- goldenkey 13y agoYou're wrong. Maybe I should hire my next team based on loop analysis ;-) http://codepad.org/kd3oOBAb http://codepad.org/kd3oOBAb
- vidarh 13y agoAnd I think this perfectly demonstrates why it is a stupid approach to take in the first place. In fact, personally I have a tendency to avoid for-loops in C because of the awful syntax; I much prefer using while-loops as I find them far clearer. In 25+ years of C, I've seen plenty of people getting for-loops wrong (making broken assumptions about what's evaluated where, and countless off by one bugs), but everyone gets while-loops. If you are going to do for-loops in C, stick with the most obvious, simplest variants possible - the moment you try to be smart, you've substantially increased the odds that a maintenance programmer will introduce a bug at one point or another.
- nitrogen 13y agoFor the sake of job security, I propose using the comma operator to put the entire loop body within the for() parentheses, and replace the block with a semicolon: // Pure C99 (prints an invalid character at the end) for( FILE *f = fopen("/etc/fstab", "r"); !feof(f) || (fclose(f), 0); putchar(fgetc(f)) ) ; // C99+POSIX for( int fd = open("/etc/fstab", O_RDONLY), c = 0; read(fd, &c, 1) || (close(fd), 0); write(1, &c, 1) ) ;
- deleted 13y ago[deleted]