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:
- Any of the common functions (
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
- If you need to read and write data by one char, you can use
putchar()functions. They are shorter than
- 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:
- Use XOR instead of
!=to save 1 symbol:
- Use dereferencing for reading the first element of an array:
- You can use assignment inside any function or operator:
- 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:
Anyone can share any thoughts about listed tricks or send any tips for C code golfing.