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 typeint
. - If you need to read and write data by one char, you can use
read()
orgetchar()
andwrite()
orputchar()
functions. They are shorter thanscanf("%c",&c)
andprintf("%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 asif(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
if
s, e.g. for comparator:(a>b)-(a<b)
.
Anyone can share any thoughts about listed tricks or send any tips for C code golfing.