[Question]
  [
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.
  
[Answer]
Use bitwise XOR to check for inequality between integers:
`if(a^b)` instead of `if(a!=b)` saves 1 character.
[Answer]
* 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](https://codegolf.stackexchange.com/questions/2078/the-alphabet-in-programming-languages/2093#2093))*
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");}
```
*(answer to [Anagram Code Golf!](https://codegolf.stackexchange.com/questions/1294/anagram-code-golf/1307#1307))*
[Answer]
# Avoid catastrophic function-argument type declarations
If you're declaring a function where all five arguments are `int`s, 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.
[Answer]
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`
[Answer]
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.
[Answer]
Certain compilers, such as GCC, allow you to omit basic `#include`s, 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.
[Answer]
# Use lambdas (unportable)
Instead of
```
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](https://codegolf.stackexchange.com/users/61563/md-xf) wrote a bash [script](https://gist.github.com/aaronryank/c6fd96d543658b19ed9268a3844d0657) that may assist in the writing of simple "lambda" functions.
Edit: This technique was previously published by Shinichiro Hamaji in [this document](http://shinh.skr.jp/dat_dir/golf_prosym.pdf).
# 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.*
[Answer]
The ternary conditional operator `?:` can often be used as a stand in for simple `if`--`else` statements at considerable savings.
Unlike [the c++ equivalent](https://codegolf.stackexchange.com/questions/132/tips-for-golfing-in-c/2228#2228) the operator [does not formally yield an lvalue](https://stackoverflow.com/q/1082655/2509), but some compilers (notably gcc) will let you get away with it, which is a nice bonus.
[Answer]
<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   
```
[Answer]
Define parameters instead of variables.
`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`.
[Answer]
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](https://codegolf.stackexchange.com/questions/284/write-an-interpreter-for-the-untyped-lambda-calculus/3290#3290).
[Answer]
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.
[Answer]
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.
[Answer]
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
[Answer]
If you ever need to output a single newline character (`\n`), don't use `putchar(10)`, use `puts("")`.
[Answer]
# Reverse Loops
If you can, try to replace
```
for(int i=0;i<n;i++){...}
```
with
```
for(int i=n;i--;){...}
```
[Answer]
# 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);`.
[Answer]
If your program is reading or writing on one in each step basis always try to use [read](http://pubs.opengroup.org/onlinepubs/009695399/functions/read.html) and [write](http://pubs.opengroup.org/onlinepubs/009695399/functions/write.html) function instead of [getchar()](http://www.cplusplus.com/reference/clibrary/cstdio/getchar/) and [putchar()](http://www.cplusplus.com/reference/clibrary/cstdio/putchar/).
**Example** ([Reverse stdin and place on stdout](https://codegolf.stackexchange.com/questions/242/reverse-stdin-and-place-on-stdout/1336#1336))
```
main(_){write(read(0,&_,1)&&main());}
```
Exercise:Use this technique to get a good score [here](http://www.spoj.pl/problems/NOP/). 
[Answer]
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  */
```
[Answer]
## Abuse dark corners of array indexing
[![enter image description here](https://i.stack.imgur.com/X4tzt.png)](https://i.stack.imgur.com/X4tzt.png)
`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.](https://codegolf.stackexchange.com/a/163258/78410)
[Answer]
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.
[Answer]
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(
```
[Answer]
# `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);
```
[Answer]
### 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 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>
[Answer]
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](http://shop.oreilly.com/product/0636920025108.do).
Usage example:
```
#define _GNU_SOURCE
#include <stdio.h>
int main(int argc, char** argv) {
  char* foo;
  asprintf(&foo, "%s", argv[1]);
  printf("%s",foo);
}
```
[Answer]
`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
[Answer]
## 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;}
```
[Answer]
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]);}`
[Answer]
Print a character then carriage return, instead of:
```
printf("%c\n",c);
```
or
```
putchar(c);putchar('\n'); // or its ascii value, whatever!
```
simply, declare c as an int and:
```
puts(&c);
```
[Answer]
## Missing `include`s and return values
As noted in the [very first answer](https://codegolf.stackexchange.com/a/2204/12012), some compilers (notably, GCC anc clang) let you get away with omitting `#include`s 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 `int`s. 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.
]