Quantcast
Viewing all articles
Browse latest Browse all 67

Answer by Toby Speight for Tips for golfing in C

Use for rather than while

Any while can be changed into a for of the same length:

while(*p++)for(;*p++;)

On its own, that's not golf. But we now have an opportunity to move an immediately-preceding statement into the parens, saving its terminating semicolon. We might also be able to hoist an expression statement from the end of the loop; if the loop contained two statements, we could also save the braces:

a=5;while(*p++){if(p[a])--a;++b;}for(a=5;*p++;++b)if(p[a])--a;

Even do...while loops should be replaced with for loops. for(;foo,bar,baz;); is shorter than do foo,bar;while(baz);.


Viewing all articles
Browse latest Browse all 67

Trending Articles