# 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 answer). Please post one tip per answer. Also, please include if your tip applies to C89 and/or C99 and if it only works on certain compilers.

• I think the biggest single-sentence hint is: Read the winning codes submitted to IOCCC.
– vsz
May 12, 2012 at 21:23

Use bitwise XOR to check for inequality between integers:

if(a^b) instead of if(a!=b) saves 1 character.

• a-b gives you the same effect. Jan 12, 2012 at 16:16
• Similarly you can use a*b instead of a&&b (has different precendence, may or may not be bad). If you know a /= -b (e.g. they are unsigned) then a||b == a+b Jun 9, 2012 at 16:35
• better yet combine it with the Elvis Operator ?: (instead of if) : for exemple to just do something if differents: a^b?_diff_:; Dec 24, 2016 at 8:52
• @OlivierDulac Is there a compiler that accepts an empty ternary if false branch? May 4, 2018 at 10:50
• @OlivierDulac You can check. From what I know, GCC has a ?: operator which is just equivalent to a ? a : b Jun 22, 2018 at 2:58
• Abuse main's argument list to declare one or more integer variables:

main(a){for(;++a<28;)putchar(95+a);}


(answer to The alphabet in programming languages)

This solution also abuses the fact that a (a.k.a. argc) starts out as 1, provided the program is called with no arguments.

• Use global variables to initialize things to zero:

t[52],i;main(c){for(;i<52;)(c=getchar())<11?i+=26:t[i+c-97]++;
for(i=27;--i&&t[i-1]==t[i+25];);puts(i?"false":"true");}


• There are no data types defined for variables, no return type of main function. Is this valid C syntax? Jan 7, 2020 at 10:23
• @Pavitra : yes, this is commonly known as the "pre-ANSI" or "K&R" C variant. A variable without a type declared explicitly is an int. This has since been deprecated and all variables and functions are required to be declared with a type. Jan 23, 2020 at 20:44

# Avoid catastrophic function-argument type declarations

If you're declaring a function where all five arguments are ints, then life is good. you can simply write

f(a,b,c,d,e){


But suppose d needs to be a char, or even an int*. Then you're screwed! If one parameter is preceded by a type, all of them must be:

f(int a,int b,int c,int*d,int e){


But wait! There is a way around this disastrous explosion of useless characters. It goes like this:

f(a,b,c,d,e) int *d; {


This even saves on a standard main declaration if you need to use the command-line arguments:

main(c,v)char**v;{


is two bytes shorter than

main(int c,char**v){


I was surprised to discover this, as I have not so far encountered it on PPCG.

• Why on Earth does that work?? Oct 24, 2014 at 8:41
• Apparently this is called K&R style and it precedes ANSI C by a decade. Oct 24, 2014 at 13:59
• Note that using K&R features and newer (say '99) features together nay or may not be possible. Depends on your compiler. May 17, 2015 at 17:47
• @dmckee is right. C99 does not allow implicit int, so you have to use -std=gnu99 and now you're not portable. In clc-speak, you're not even writing "C" code per se, but "Gnu99-C". 'Round here we mostly ignore that, but it's good to mention it if you post code that is compiler-specific. Sometimes people actually do download and execute these programs of ours. :) Jul 13, 2015 at 20:58
• @luserdroog: You can use -std=c89 to tell gcc or clang to compile your code according to that older standard, which does allow implicit int with only a warning. Jun 14, 2018 at 15:09

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 executed
else
printf("failed\n");

}


Outputs: 1 2

• Doesn't work if one of the statements is break. Apr 8, 2017 at 2:46
• @MaxLawnboy because break is a statement, and this answer is talking about expressions.
– Maya
Feb 5, 2018 at 16:25

Instead of >= and <= you can simply use integer division (/) when the compared values are above zero, which saves one character. For example:

putchar(c/32&&126/c?c:46); //Prints the character, but if it is unprintable print "."


Which is of course still shrinkable, using for example just > and ^ (a smart way to avoid writing && or || in some cases).

putchar(c>31^c>126?c:46);


The integer division trick is for example useful to decide whether a number is less than 100, as this saves a character:

a<100 vs 99/a


This is also good in cases when higher precedence is needed.

• You can write putchar(c>31&c<127?c:46); Feb 24, 2019 at 19:33

Certain compilers, such as GCC, allow you to omit basic #includes, param, and return types for main.

The following is a valid C89 and C99 program that compiles (with warnings) with GCC:

main(i) { printf("%d", i); }


Notice that the #include for stdio.h is missing, the return type for main is missing, and the type declaration for i is missing.

• Technically it's not valid according to standards as main accepts zero or two parameters, not one. Not that anyone cares in code golf. Jan 2, 2014 at 22:24
• Calling printf() (or any variadic function) without a prototype causes undefined behaviour. GCC does not compile standard C by default. If you invoke gcc in C89 mode (gcc -ansi -pedantic) or C99 mode (gcc -std=c99 -pedantic), you will get quite a few complaints, at least in the latter case. Oct 27, 2014 at 13:31
• @NisseEngström: the calling conventions on mainstream C implementations make it safe to call variadic functions without prototypes. So most C implementations do define the behaviour. Jun 14, 2018 at 15:12

# Use lambdas (unportable)

f(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 support)

qsort_b(a,b,4,^(const void*a,const void*b){return*(int*)a>*(int*)b?1:-1;});


try something like

qsort(a,b,4,"\x8b\7+\6\xc3");


...where the string literal contains the machine language instructions of your "lambda" function (conforming to all platform ABI requirements).

This works in environments in which string constants are marked executable. By default this is true in Linux and OSX but not Windows.

One silly way to learn to write your own "lambda" functions is to write the function in C, compile it, inspect it with something like objdump -D and copy the corresponding hex code into a string. For example,

int f(int*a, int*b){return *a-*b;}


...when compiled with gcc -Os -c for a Linux x86_64 target generates something like

0:   8b 07                   mov    (%rdi),%eax
2:   2b 06                   sub    (%rsi),%eax
4:   c3                      retq


MD XF wrote a bash script that may assist in the writing of simple "lambda" functions.

# GNU CC goto:

You can call these "lambda functions" directly but if the code you're calling doesn't take parameters and isn't going to return, you can use goto to save a few bytes. So instead of

((int(*)())L"ﻫ")();


or (if your environment doesn't have Arabic glyphs)

((int(*)())L"\xfeeb")();


Try

goto*&L"ﻫ";


or

goto*&L"\xfeeb";


In this example, eb fe is x86 machine language for something like for(;;); and is a simple example of something that doesn't take parameters and isn't going to return :-)

It turns out you can goto code that returns to a calling parent.

#include<stdio.h>
int f(int a){
if(!a)return 1;
goto*&L"\xc3c031"; // return 0;
return 2; // never gets here
}
int main(){
printf("f(0)=%d f(1)=%d\n",f(0),f(1));
}


The above example (might compile and run on Linux with gcc -O) is sensitive to the stack layout.

EDIT: Depending on your toolchain, you may have to use the -zexecstack (for gcc) or -Wl,-z,execstack (for clang) compile flag.

If it isn't immediately apparent, this answer was mainly written for the lols. I take no responsibility for better or worse golfing or adverse psychological outcomes from reading this.

• I've just written a script to read parts of a C function from standard in and print a C lambda. Might be worth mentioning in your answer, might just be nice for you to see since you taught me to do this in the first place. Feb 3, 2018 at 1:24

The ternary conditional operator ?: can often be used as a stand in for simple if--else statements at considerable savings.

Unlike the c++ equivalent the operator does not formally yield an lvalue, but some compilers (notably gcc) will let you get away with it, which is a nice bonus.

• Addition: If you only need an if, but not an else then the ternary can still be useful. Apr 27, 2011 at 20:29
• && and || can also be used: if(x==3)f() becomes with your suggestion x==3?f():0, and can be further improved to x==3&&f(). But be careful with operator precedence - if f() is replaced with y=1, then the && solution requires an extra set of parenthesis. Jan 12, 2012 at 16:20
• I'd never realized that gcc's ?: yields an lvalue. Can I use that in production code? lol Jan 12, 2012 at 19:55
• @ugoren: x==3&&f() can be further golfed to x^3||f() Dec 26, 2012 at 12:04
• @fgrieu, yes, though it's not exactly the topic here (this answer suggests it). Dec 26, 2012 at 17:25

http://graphics.stanford.edu/~seander/bithacks.html

Bits are nice.

~-x = x - 1
-~x = x + 1


But with different precedences, and don't change x like ++ and --. Also you can use this in really specific cases: ~9 is shorter than -10.

if(!(x&y)) x | y == x ^ y == x + y
if(!(~x&y)) x ^ y == x - y


That's more esoteric, but I've had occassion to use it. If you don't care about short-circuiting

x*y == x && y
if(x!=-y) x+y == x || y


Also:

if(x>0 && y>0) x/y == x>=y

• The last tip ((x/y) == (x>=y)) is really useful. Sep 6, 2012 at 9:11
• Some of these don't work on my machine (I guess because these hacks largely rely on "undefined" behavior) Jan 20, 2021 at 17:01

f(x){int y=x+1;...}

f(x,y){y=x+1;...}

You don't need to actually pass the second parameter.

Also, you can use operator precedence to save parenthesis.
For example, (x+y)*2 can become x+y<<1.

• Or just x+y*2, saving yet another char. Feb 2, 2014 at 8:29
• @B1KMusic, x+y*2 isn't the same, due to operator precedence. Feb 2, 2014 at 12:13
• Right, lol. That would be x+(y*2). I was fixated on the x+y<<1 example, assuming it was being evaluated as x+(y<<1), and suggested the *2 instead. I didn't know bitshift operations were evaluated as e.g. (x+y)<<2 Feb 3, 2014 at 2:46

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. (The old a[x] == x[a] trick.)

But, there's more! Then you can have pointer args and returns in functions that are shorter than macros (especially if you abbreviate 'return'):

f(x){return x M;} //implicit ints, but they work like pointers
#define f(x) (x M)


To make a cursor from a pointer, you subtract the base-pointer, yielding a ptrdiff_t, which truncates into an int, losses is yer biz.

int p = sbrk(sizeof(whatever)) - m;
strcpy(m+p, "hello world");


This technique is used in my answer to Write an interpreter for the untyped lambda calculus.

The ternary operator ?: is unusual in that it has two separate pieces. Because of this, it provides a bit of a loophole to standard operator precedence rules. This can be useful for avoiding parentheses.

Take the following example:

if (t()) a = b, b = 0;  /* 15 chars */


The usual golfing approach is to replace the if with &&, but because of the low precedence of the comma operator, you need an extra pair of parentheses:

t() && (a = b, b = 0);  /* still 15 chars */


The middle section of the ternary operator doesn't need parentheses, though:

t() ? a = b, b = 0 : 0;  /* 14 chars */


Similar comments apply to array subscripts.

• In this example, b-=a=b is even shorter. The ?: trick is still helpful, -= because also has low preference. May 8, 2012 at 7:30
• Good point; my example was needlessly complex. May 8, 2012 at 8:54
• Another point is that sometimes you want to flip the condition: for x>0||(y=3), x>0?0:(y=3) is useless, but x<1?y=3:0 does the job. May 8, 2012 at 10:44
• both clang and gcc allow for an empty true case in the ternary. If omitted, its value is the value of the condition. For example, x>5?:y=1 Apr 9, 2019 at 4:56

Any part of your code that repeats several times is a candidate for replacement with the pre-processor.

#define R return


is a very common use case if you code involves more than a couple of functions. Other longish keywords like while, double, switch, and case are also candidates; as well as anything that is idomatic in your code.

I generally reserve uppercase character for this purpose.

• A shorter replacement would be -DR=return. Note that if you include certain characters, it may become necessary to have single or double quotes around the define -DP='puts("hello")'.
– user77406
Jul 25, 2018 at 18:29

Since usually EOF == -1, use the bitwise NOT operator to check for EOF: while(~(c=getchar())) or while(c=getchar()+1) and modify value of c at every place

• I don't know C well enough, but wouldn't while(1+c=getchar()) work? May 4, 2015 at 16:33
• @ɐɔıʇǝɥʇuʎs No. The addition operator + has higher precedence than the assignment operator =, so 1+c=getchar() is equivalent to (1+c)=getchar(), which does not compile because (1+c) is not an lvalue. May 19, 2015 at 18:56

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

# Reverse Loops

If you can, try to replace

for(int i=0;i<n;i++){...}


with

for(int i=n;i--;){...}

• for(;++i<n;){...} is even shorter if u declare i as a function parameter like fn(i) May 18, 2021 at 6:55

# 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);.

• The for loop allows up to two statements this way without braces, where the while loop only allows one. You could have avoided the braces in the first example with a comma as follows: a=5;while(*p++)if(p[a])--a,++b; Mar 21 at 18:49

If your program is reading or writing on one in each step basis always try to use read and write function instead of getchar() and putchar().

Example (Reverse stdin and place on stdout)

main(_){write(read(0,&_,1)&&main());}


Exercise:Use this technique to get a good score here.

• What do you mean by in each step basis ? Apr 26, 2011 at 14:46
• Casey: I guess they mean if the program is reading something, operates on it, and writes output. In a streaming manner, so to say. As opposed to an approach where all the input has to be read and handled at once.
– Joey
May 27, 2011 at 13:34
• That stack manipulation is gorgeous. May 21, 2015 at 19:53
• On what ABI and compiler does this work? It does not work on x86-64 (GCC 8.3). Jun 19, 2021 at 16:02

Make use of return values to zero stuff. If you call some function, and that function returns zero under normal conditions, then you can place it in a location where zero is expected. Likewise if you know the function will return non-zero, with the addition of a bang. After all, you don't do proper error handling in a code golf in any case, right?

Examples:

close(fd);foo=0;   →  foo=close(fd);    /* saves two bytes */
putchar(c);bar=0;  →  bar=!putchar(c);  /* saves one byte  */

1. Use *a instead of a[0] for accessing the first element of an array.

2. Relational operators (!=, >, etc.) give 0 or 1. Use this with arithmetic operators to give different offsets depending on whether the condition is true or false: a[1+2*(i<3)] would access a[1] if i >= 3 and a[3] otherwise.

• a[i<3?3:1] is two characters shorter than a[1+2*(i<3)]. Jun 13, 2015 at 4:15

You may look into the IOCCC archives (international obfuscated C code contest).

One notable trick is to #define macros whose expansion has unbalanced braces/parentheses, like

#define P printf(

• The mismatched parentheses have no value in themselves. The point is to define as much of the repeating pattern as possible. You might want to go further, with #define P;printf(. May 8, 2012 at 7:25
• How does this shorten byte count? Perhaps provide an example? Sep 19, 2016 at 5:07
• @Cyoce See for example this answer. Apr 30, 2018 at 12:56

## Abuse dark corners of array indexing

i[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 see an array indexing expression (whatever)[x] where whatever requires wrapping in parens and x doesn't, but when you see one, you can swap the two positions and write x[whatever] to save two bytes.

A real golfing example.

# dprintf for conditional printing

As you may know, printing something by a condition can be done with ?:, && or ||:

cond&&printf("%d\n",n);
cond||printf("%d\n",n);
cond?:printf("%d\n",n);


Another interesting idea is to use dprintf, which is the same as printf except that it takes an extra argument, specifying the output file descriptor. It will only output to STDOUT if said argument is equal to 1. This can be abused to potentially save a few bytes over the previously mentioned methods:

x-1||printf("%d\n",n);
dprintf(x,"%d\n",n);


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 argument is stored into the same CPU register as the return value.

Note: As noted in one comment, this is undefined behaviour and not guaranteed to work for every operation. And any compiler optimization will just skip over it.

### X-Macros

Another useful feature: X-Macros can help you when you have a list of variables and you need to do some operation which involve all of them:

https://en.wikipedia.org/wiki/X_Macro

• I quoted this and I was corrected, This is simply not true. It will only work with multiplications and divisions and when optimizations are turned off. This is because both operations happen to put their results in eax which is the common register for return. Parameters are stored either in the stack or ecx or edx. Try it yourself. Apr 9, 2017 at 20:15
• You are right, it's undefined behaviour, it also depends on the compiler and on the architecture, I usually check with gcc on x86 and armv7 before posting any answer using this trick. And of course if you enable optimization, any smart compiler would just delete the unnecessary multiplication.
– G B
Apr 10, 2017 at 6:25
• I've seen this work with GCC but not others May 21, 2017 at 7:10
• @Gaspa79: gcc with -O0 always chooses to evaluate expressions in the return-value register. I've looked at x86, ARM, and MIPS at least (on gcc.godbolt.org), and gcc seems to go out of its way to do that at -O0. But remember if you take advantage of this, the language you're programming in is gcc -O0, not C, and you should label your answer accordingly, not as C. It fails at any optimization level other than -O0 debug mode, and doesn't work with clang IIRC. Jun 14, 2018 at 15:18
• I answered an SO Q&A about exactly why this works with gcc -O0, under what conditions: Return value in unused parameter when falling off the end of a non-void function (I didn't get into the GCC source code to look for that level of detail, but covered why assignment always "works": stores need the source value in a register, so GCC can't ever avoid evaluating into some register. And it always picks the return-value register.) Sep 20, 2021 at 14:13

Using asprintf() saves you the explicit allocating and also measuring the length of a string aka char*! This isn't maybe too useful for code golfing, but eases the everyday work with a char arrays. There are some more good advises in 21st Century C.

Usage example:

#define _GNU_SOURCE
#include <stdio.h>

int main(int argc, char** argv) {
char* foo;
asprintf(&foo, "%s", argv[1]);
printf("%s",foo);
}


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 loop

for(int i=0;i<n;b(i++))a(i); -3 more for moving all but one statement into the top and out of the main loop, removing the braces

• Using the comma operator is another way to avoid braces in some cases. Jun 14, 2018 at 15:22

## 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 boilerplate for defining a function.

#define D(f,...)f(x){return __VA_ARGS__;}
D(f,x+2)
D(g,4*x-4)
D(main,g(4))


Program result is its status value returned to the OS or controlling shell or IDE.

Using __VA_ARGS__ allows you to use the comma operator to introduce sequence points in these function-expressions. If this is not needed, the macro can be shorter.

#define D(f,b)f(x){return b;}

• As an alternative to __VA_ARGS__, there's the following GNU extension: D(f,b...)f(x){return b;}
– Maya
Jun 25, 2021 at 18:39
1. use scanf("%*d "); to read the dummy input. (in case that input is meaningless in further program) it is shorter than scanf("%d",&t); where you also need to declare the variable t.

2. storing characters in int array is much better than character array. example.

s[],t;main(c){for(scanf("%*d ");~(c=getchar());s[t++]=c)putchar(s[t]);}

• Actually, I use %*d not only in Golf because it's also useful in situations where one would, for example, want to skip a newline in scanf("%[^\n]%*c",str); :) Dec 22, 2013 at 21:21

## Missing includes and return values

As 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 goes well, it might cause problems in some cases, since the implicit declarations of standard library functions inside the source code will cause the compiler to treat return values as ints. For example, the code

char*p=getenv("PATH");


wont work as expected on a 64-bit platform since getenv returns a 64-bit memory address which doesn't fit into an int.

In this case, there are at least three ways to use getenv without errors.

• Include the header file as follows.

#include<stdlib.h>
char*p=getenv("PATH");


This is the right way™, but not very golfy; it costs 19 bytes.

• Declare getenv with the pointer as follows.

char*getenv(),*p=getenv("PATH");


This costs 10 bytes.

• Finally, unless your code wouldn't work on 32-bit platforms, compile your code on one of those or with the -m32 flag (gcc). This costs 0 bytes.

# Try cpow() instead of cos()

double y=cos(M_PI*2*x);


try something like

double y=cpow(-1,x*2);


This uses Euler's formula, a little complex analysis and the observation that assigning a complex to a double yields the real part (careful with variadic function calls and other subtleties).

$$\\cos 2\pi x+j\sin 2\pi x=e^{j2\pi x}=e^{j\pi 2x}=\left(-1\right)^{2x}\$$

This type of trick can be used to reduce

double y=cpow(-1,x/2);


into

double y=cpow(1i,x);


because $$\\left(-1\right)^\frac{x}{2}=j^\frac{2x}{2}=j^x\$$

Edit: Equations now inline $$\\LaTeX\$$ instead of images.