Quantcast
Viewing all articles
Browse latest Browse all 67

Answer by Nicholas Sudsgaard for Tips for golfing in C

Use strings as arrays

Suppose you had an array like the following.

c[]={1,2,3,4,5,6,7,8,9,10};// ...some code here...printf("%d",c[i]);

You can make this at least 9 bytes shorter using this method.

char*x,*c="abcdefghij"; // initialize like this if you already have a 'char *' declaration somewhere.c[]=L"abcdefghij";      // initialize like this you do not (thanks to @ceilingcat for teaching me this one).// ...some code here...printf("%d",c[i]-97);

You can also do something similar with an array of strings.

char*c[]={"cat","dog","mouse","fish"};// ...some code here...puts(c[i]);

you can reduce 2 bytes. However, this is slightly more tricker to get right. This usually only works when the length of the strings in the array only differ by 2 at most.

The '.' characters are padding that allows you to access each "substring" within the string using a multiple of a fixed offset.

char*c="cat\0..dog\0..mouse\0fish";// ...some code here...puts(c+6*i);

If the order of the strings do not matter, it is best to place the longest string at the end as, you may be able to save some bytes worth of padding.

char*c="cat\0.dog\0.fish\0mouse";// ...some code here...puts(c+5*i);

This is a useful trick that I have used to reduce quite a lot of bytes in the following answers.

`lol` is an ambigram, `dad` isn't

Can the chefs go?


Viewing all articles
Browse latest Browse all 67

Trending Articles