Tips and Tricks for Code Golfing in C

I think that every language that is widely used in code golf should have this kind of topic. C is a popular choice for golfers, so why not share a couple of tips and tricks for this language. Most of these techniques can be used in C++ code too.

WIP: looking for additional information

  • You can write your main function without a type and return statement: main(){/*your code*/}.
  • Any of the common functions (scanf, printf, etc) can be used without including libraries.
  • You can declare variables in global space without declaring a type: a,b,c;main(). Here a, b and c will be of type int.
  • If you need to read and write data by one char, you can use read() or getchar() and write() or putchar() functions. They are shorter than scanf("%c",&c) and printf("%c",c).
  • Sometimes, you can shorten your code by using recursion instead of loops. Your main() can also be recursively used.
  • You can use a comma operator (,) for executing multiple operations in one line without using brackets: for(;;)i++,d++;.
  • Use XOR instead of != to save 1 symbol: if(a^b) same as if(a!=b).
  • Use dereferencing for reading the first element of an array: *c (2 bytes), c[0] (4 bytes).
  • You can use assignment inside any function or operator: printf("%s",(c=b)?"true":"false");.
  • Also, instead of ternary for strings, you can split them with ‘\0’ and choose the needed part: "false\0true"+1 (will choose the “true” part).
  • Sometimes, you can use bool operators in equations avoiding ifs, e.g. for comparator: (a>b)-(a<b).

:fox_face: Anyone can share any thoughts about listed tricks or send any tips for C code golfing.


You can replace chars with their ASCII index, example putchar(10) instead of putchar('\n')

You can replace for (int i=0;i<n;i++) with while(n--) if you don’t need to reuse n and you don’t need to read i

1 Like

More Tips
The first argument to main will be an integer set to 1: in main(a), a == 1.
If you use libraries, write #import<library> instead of #include<library>.
(Kind of obvious:) Use for(;;) instead of while(1) for an infinite loop.