Quantcast
Channel: Tips for golfing in C - Code Golf Stack Exchange
Browsing latest articles
Browse All 67 View Live

Answer by vengy for Tips for golfing in C

Omit Array LengthIf you don't mind possible undefined behavior, define an array C[] (compiler assumes to have one element) and then rely upon the adjacent memory as usable space.C[];main(){...}Try it...

View Article


Answer by Nicholas Sudsgaard for Tips for golfing in C

Use strings as arraysSuppose 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...

View Article


Answer by l4m2 for Tips for golfing in C

Conditional printf different formatx>0?printf("%c",x):printf("%d",-x);printf(x>0?"%c":"%.f",x,0.-x); // float goes different registersUsed here

View Article

Answer by c-- for Tips for golfing in C

Abuse wchar_t to print one character from a stringIn a little-endian architecture, you can replaceputchar("string"[i])withprintf(L"string"+i)to save a byte.

View Article

Answer by naffetS for Tips for golfing in C

Use bitwise operators to convert characters to uppercase/lowercase. Bitwise AND with 95 (or '_') to convert to uppercase, bitwise OR with 32 (or '') to convert to lowercase, and to invert case, bitwise...

View Article


Answer by badatgolf for Tips for golfing in C

Use bitwise operators for boolean conditionsFor example:if(a||b) /* do something */This saves one byte:if(a|b) /* do something */Respectively, a!=b becomes a^b and a&&b becomes a&bAn...

View Article

Answer by dingledooper for Tips for golfing in C

dprintf for conditional printingAs you may know, printing something by a condition can be done with ?:, && or...

View Article

Answer by AZTECCO for Tips for golfing in C

Sometimes you can use floating point where you don't expect to.Ignoring possible floating point imprecision issues you still can use them with many operators you wouldn't normally expect :++--...

View Article


Image may be NSFW.
Clik here to view.

Answer by Bubbler for Tips for golfing in C

Abuse dark corners of array indexingi[array] desugars into *(i+array), and since + is commutative for pointer+integer too, it is equivalent to *(array+i) and therefore array[i].It's not very common to...

View Article


Answer by l4m2 for Tips for golfing in C

Omit returnSurprised that only this answer provided a similar situation Instead of return x; in the end, use g=x; where g is a global variable.In other situations, it may be more shortened. Refer here...

View Article

Answer by Bubbler for Tips for golfing in C

Favor recursion over loops, especially if going forwards then backwardsLoops, 67 bytesl;f(char*s){for(l=0;s[l];)putchar(s[l++]);for(;l;)putchar(s[--l]);}Try it online!Recursion, 47...

View Article

Answer by S.S. Anne for Tips for golfing in C

Abuse two's complementA lot of expressions can be changed by (ab)using two's complement. Take this for example:getchar()+1If you need higher precedence, you can use this:-~getchar()Or, if you're using...

View Article

Answer by ceilingcat for Tips for golfing in C

Exploit ASLROn systems with ASLR (Address Space Layout Randomization), the address of a stack variable can be used as a one time pseudorandom number. Instead of something like...srand(time(0));...try...

View Article


Answer by Jonathan Frech for Tips for golfing in C

Calculating \$\lceil\log_{10}(n)\rceil\$Especially in challenges where properties of decimal representations are of interest, one needs to find a number's decimal representation's length, or for...

View Article

Answer by r3mainer for Tips for golfing in C

Get the length of a string with puts() instead of strlen()According to the standard C specification, puts() returns a non-negative integer on success. In practice, most C libraries seem to treat...

View Article


Answer by Jonathan Frech for Tips for golfing in C

Boolean constant string selection when the selector's true value is guaranteed to be one larger than the second option's lengthAt its heart, this tip attempts to golf a ternary if of the form...

View Article

Answer by Toby Speight for Tips for golfing in C

Use for rather than whileAny 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...

View Article


Answer by Geo for Tips for golfing in C

Use recursion over loops. Recursive examplef(){printf("infiniteloop");f();}For loop equivalent is 3 bytes longer.f(){for(;;)printf("infiniteloop");}

View Article

Answer by Peter Cordes for Tips for golfing in C

When your algorithm produces output in reverse order, take a pointer to the end of a buffer and write it in decreasing order, returning a pointer to the first element. It's up to the caller to supply a...

View Article

Answer by ceilingcat for Tips for golfing in C

Set an array of int to the same value (C99, Linux, BSD, OSX)Instead ofint a[n]=...,x=...;for(int i=n;i--;)a[i]=xTry something likeint a[n]=...,x=...;wmemset(a,x,n);On MSVC on Windows, wmemset() works...

View Article

Answer by Jonathan Frech for Tips for golfing in C

Inverse flag updateSometimes a challenge asks to determine a data set's specific boolean property. To avoid the unacceptably long return keyword, I often use a flag variable which gets updated in a...

View Article


Answer by Steadybox for Tips for golfing in C

Sometimes, albeit rarely, if your code contains many for loops, #define F for( may save a byte or two (especially if some of the loops have an empty init section).If it is applicable to your situation,...

View Article


Answer by gastropner for Tips for golfing in C

Whenever a certain function is called several times, it's common to #define it to something shorter. However, certain compilers (MinGW and clang as far as I know) allows for something even more compact...

View Article

Answer by Colera Su for Tips for golfing in C

Inline arraysIf you need a non-int constant array and just use it once, you can dofloat f(a){return (float[]){.3,.2,.7}[a];}instead offloat z[]={.3,.2,.7};float f(a){return z[a];}to save 3 bytes.(In...

View Article

Answer by ceilingcat for Tips for golfing in C

Try cpow() instead of cos()Instead ofdouble y=cos(M_PI*2*x);try something likedouble y=cpow(-1,x*2);This uses Euler's formula, a little complex analysis and the observation that assigning a complex to...

View Article


Answer by MD XF for Tips for golfing in C

Use s[i] instead of i<strlen(s) in string-handling loopsFor example:for(i=0;i<strlen(s);i++)s[i]=s[i+1];can be shortened to:for(i=0;s[i];i++)s[i]=s[i+1];

View Article

Answer by MD XF for Tips for golfing in C

Use #define instead of functions when possibleFor example:f(int i,char*s){/*do something with i and s*/;}Using #define can eliminate the argument list type, curly-braces and closing semicolon:#define...

View Article

Answer by ceilingcat for Tips for golfing in C

Overload functions (unportable)Instead of declaring multiple functions...d(x){return x*2;}float r(float x){return 1/sqrt(x);}...printf( "%d %f\n", d(2), r(2) );...declare one "function" that does...

View Article

Answer by Karl Napf for Tips for golfing in C

Swap variablesIf you ever need to swap variables, don't use the pattern with an extra variable or that addition-subtraction-method, just do some chained XORing:a^=b^=a^=b;

View Article



Answer by G B for Tips for golfing in C

Assign instead of return.This is not really standard C, but works with every compiler and CPU that I know of:int sqr(int a){return a*a;}has the same effect as:int sqr(int a){a*=a;}Because the first...

View Article

Answer by ceilingcat for Tips for golfing in C

Use lambdas (unportable)Instead off(int*a,int*b){return*a>*b?1:-1;}...qsort(a,b,4,f);or (gcc only)qsort(a,b,4,({int L(int*a,int*b){a=*a>*b?1:-1;}L;}));or (clang with blocks...

View Article

Answer by Dennis for Tips for golfing in C

import if you have toAs noted in the very first answer, some compilers (notably, GCC and clang) let you get away with omitting #includes for standard library functions.Even if you can't just remove the...

View Article

Answer by Dennis for Tips for golfing in C

Missing includes and return valuesAs noted in the very first answer, some compilers (notably, GCC anc clang) let you get away with omitting #includes for standard library functions.While that usually...

View Article


Answer by ceilingcat for Tips for golfing in C

Reverse LoopsIf you can, try to replacefor(int i=0;i<n;i++){...}withfor(int i=n;i--;){...}

View Article

Answer by luser droog for Tips for golfing in C

Go functional!If you can reduce your problem to simple functions with the same signature and defined as single expressions, then you can do better than #define r return and factor-out almost all of the...

View Article

Answer by aloisdg for Tips for golfing in C

When you have to walk a string you can walk the pointer instead of incrementing the index.Code :#include <stdio.h>// print each charvoid f(char* s) { for (int i=0;s[i];i++) putchar(s[i]);}// same...

View Article


Answer by tox123 for Tips for golfing in C

Knowing basic logical equalities might be able to save a couple bytes. For instance, instead of if (!(a&&b)){} try instead using DeMorgan's law if (!a||!b){}. The same applies to bitwise...

View Article


Answer by MegaTom for Tips for golfing in C

for(int i=0;i<n;i++){a(i);b(i);}can be made shorter a few ways:for(int i=0;i<n;){a(i);b(i++);}-1 for moving the ++ to the last i in the loopfor(int i=0;i<n;b(i++))a(i);-3 more for moving all...

View Article

Answer by Cole Cameron for Tips for golfing in C

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 callsInstead of this:r = /* Some random expression...

View Article

Answer by Spikatrix for Tips for golfing in C

For scanning a string into an array, you can usegets(str);instead of scanf("%s",str);

View Article

Answer by takra for Tips for golfing in C

Use bitwise and (&) when comparing boolean expressions to save one byte. Example: if(i^2&k/3) DoSomething;Really, really useful when combined with the other tips

View Article


Answer by Abr001am for Tips for golfing in C

instead of the printf loopfor(i=1;i<12;i++){if(!i%3)printf("\n");printf("%d",i);}just usefor(i=1;i<12;i++) printf("%c%d",!(i%3)*10,i);it helps me so much .@SamHocevar 's answer (shorter by...

View Article

Answer by user12205 for Tips for golfing in C

If you ever need to output a single newline character (\n), don't use putchar(10), use puts("").

View Article


Answer by feersum for Tips for golfing in C

Avoid catastrophic function-argument type declarationsIf you're declaring a function where all five arguments are ints, then life is good. you can simply writef(a,b,c,d,e){But suppose d needs to be a...

View Article

Answer by luser droog for Tips for golfing in C

Use cursors instead of pointers. Snag the brk() at the beginning and use it as a base-pointer.char*m=brk();Then make a #define for memory access.#define M [m]M becomes a postfix * applied to integers....

View Article


Answer by Casey for Tips for golfing in C

The comma operator can be used to execute multiple expressions in a single block while avoiding braces:main(){ int i = 0; int j = 1; if(1) i=j,j+=1,printf("%d %d\n",i,j); // multiple statements are all...

View Article

Tips for golfing in C

What general tips do you have for golfing in C? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to C (e.g. "remove comments" is not an...

View Article

Answer by c-- for Tips for golfing in C

Abuse implicit conversionsIf you need to check if a variable is in a given range (say islower(3))...Instead of96<c&c<123... try something likec-97<26u // this also has the advantage of...

View Article

Answer by None1 for Tips for golfing in C

Access the first element of array using unary *Arrays are similar to const pointers, so instead of a[0], you can use *a, saves 2 bytes.

View Article


Answer by Rémi for Tips for golfing in C

If you have some variables declared in a row :int a,b,c,d;You can access b by (&a)[1], or c by (&a)[2] ...It can be interesting there :i?a=k:i-1?b=k:i-2?c=k:(d=k);VS(&a)[i]=k;You could have...

View Article

Browsing latest articles
Browse All 67 View Live


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