Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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' );
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading