'How can I combine two similar while loops in C?
I am going through K&R C and am currently trying to make my code for Exercise 1-22 more readable. I have two loops like so
while (spaces != 0) {
buf[pos]=' ';
++pos;
--spaces;
}
while (tabs != 0) {
buf[pos]='\t';
++pos;
--tabs;
}
spaces and tabs are integers which count preceding spaces and tabs respectively and buf[pos] is a char array. The goal is to insert preceding spaces and tabs when a character is encountered. spaces is set to 0 when a tab is encountered and tabs is set to 0 when a space is encountered.
Is there any other way of expressing these two loops or is this the most readable form?
Solution 1:[1]
That's is quite readable.
I would go with the following:
while ( spaces-- )
buf[ pos++ ] = ' ';
while ( tabs-- )
buf[ pos++ ] = '\t';
If you really wanted to eliminate the duplication, use a function.
void append_n_ch( char *buf, size_t *pos, size_t count, char ch ) {
while ( count-- ) {
buf[ (*pos)++ ] = ch;
}
append_n_ch( buf, &pos, spaces, ' ' );
append_n_ch( buf, &pos, tabs, '\t' );
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
