Home > Net >  How can I combine two similar while loops in C?
How can I combine two similar while loops in C?

Time:03-30

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?

CodePudding user response:

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' );

CodePudding user response:

Maybe you could do something like:

   while (spaces != 0 && tabs!=0) {
    if(buf[pos]=' '){  pos;--spaces;}
    else{  pos; --tabs;}
  • Related