Quantcast
Channel: Tips for golfing in C - Code Golf Stack Exchange
Viewing all articles
Browse latest Browse all 67

Answer by Cole Cameron for Tips for golfing in C

$
0
0

Here are a few tips I've used to my advantage. I've shamelessly stolen them from others, so credit to anyone but me:

Combine assignment with function calls

Instead of this:

r = /* Some random expression */printf("%d", r);

Do this:

printf("%d", r = /* Some random expression */);

Initialize multiple variables together (when possible)

Instead of this:

for(i=0,j=0;...;...){ /* ... */ }

Do this:

for(i=j=0;...;...){ /* ... */ }

Collapse zero/nonzero values

This is a neat trick I picked up from someone here (don't remember who, sorry). When you have an integer value and you need to collapse it to either 1 or 0, you can use !! to do so easily. This is sometimes advantageous for other alternatives like ?:.

Take this situation:

n=2*n+isupper(s[j])?1:0; /* 24 */

You could instead do this:

n=n*2+!!isupper(s[j]); /* 22 */

Another example:

r=R+(memcmp(b+6,"---",3)?R:0); /* 30 */

Could be rewritten as:

r=R+R*!!memcmp(b+6,"---",3)); /* 29 */

Viewing all articles
Browse latest Browse all 67

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>