| Bytes | Lang | Time | Link |
|---|---|---|---|
| nan | 170331T051322Z | ceilingc | |
| nan | 110424T204550Z | Casey | |
| nan | 240522T072329Z | Rém | |
| nan | 240423T231713Z | c-- | |
| nan | 240113T015408Z | vengy | |
| nan | 231223T125343Z | Nicholas | |
| nan | 161229T053858Z | ceilingc | |
| nan | 230705T162324Z | l4m2 | |
| nan | 220415T132542Z | badatgol | |
| nan | 190913T010239Z | Jonathan | |
| nan | Abuse wchar_t to print one character from a string | 220805T164745Z | c-- |
| 032 | Use bitwise operators to convert characters to uppercase/lowercase. Bitwise AND with 95 or '_' to convert to uppercase | 220426T195452Z | naffetS |
| nan | 121028T073105Z | luser dr | |
| nan | 211124T091315Z | dingledo | |
| nan | 211117T082113Z | AZTECCO | |
| nan | 210729T003412Z | Bubbler | |
| nan | 200519T093828Z | l4m2 | |
| nan | 150504T110804Z | Abr001am | |
| nan | Favor recursion over loops | 200402T012732Z | Bubbler |
| nan | 200221T021739Z | S.S. Ann | |
| nan | 200216T043248Z | ceilingc | |
| nan | 180720T084322Z | Toby Spe | |
| nan | 170920T080631Z | ceilingc | |
| nan | 190416T074014Z | r3mainer | |
| nan | 180923T040408Z | Jonathan | |
| nan | 180709T161157Z | Geo | |
| nan | When your algorithm produces output in reverse order | 180622T021604Z | Peter Co |
| nan | Set an array of int to the same value C99 | 180616T041557Z | ceilingc |
| nan | 180502T194002Z | Jonathan | |
| nan | Sometimes | 180113T024850Z | Steadybo |
| nan | Whenever a certain function is called several times | 171231T090227Z | gastropn |
| nan | 171127T033421Z | Colera S | |
| nan | 161030T050005Z | Dennis | |
| nan | 170521T043332Z | MD XF | |
| nan | 170521T042833Z | MD XF | |
| nan | 170108T073646Z | G B | |
| nan | 170227T101207Z | Karl Nap | |
| nan | 161017T183525Z | Dennis | |
| nan | 160929T002105Z | ceilingc | |
| nan | 160918T222637Z | luser dr | |
| nan | 160717T214229Z | aloisdg | |
| nan | Knowing basic logical equalities might be able to save a couple bytes. For instance | 160618T215428Z | tox123 |
| nan | 160203T215120Z | MegaTom | |
| nan | Here are a few tips I've used to my advantage. I've shamelessly stolen them from others | 160201T195015Z | Cole Cam |
| nan | For scanning a string into an array | 150621T060709Z | Spikatri |
| nan | Use bitwise and & when comparing boolean expressions to save one byte. | 150613T000442Z | takra |
| nan | If you ever need to output a single newline character \n | 150504T104800Z | user1220 |
| nan | 141024T080401Z | feersum | |
| nan | 110424T020130Z | dmckee - | |
| nan | 140725T084404Z | es1024 | |
| nan | Certain compilers | 110424T011018Z | Casey |
| nan | Make use of return values to zero stuff. If you call some function | 140106T001341Z | MvG |
| 001 | Since usually EOF == 1 | 110425T140432Z | Lowjacke |
| nan | Using asprintf saves you the explicit allocating and also measuring the length of a string aka char*! | 131219T131635Z | klingt.n |
| nan | Print a character then carriage return | 131217T020249Z | moala |
| nan | Instead of >= and <= you can simply use integer division / when the compared values are above zero | 130416T220941Z | Fors |
| nan | 120615T214141Z | walpen | |
| nan | 120508T055022Z | Andreas | |
| nan | The ternary operator ? is unusual in that it has two separate pieces. Because of this | 120507T023532Z | breadbox |
| nan | 120315T112058Z | Neeraj G | |
| nan | 120112T130755Z | ugoren | |
| nan | 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. | 110426T122433Z | Quixotic |
| nan | 110425T122625Z | Lowjacke | |
| nan | 110424T202727Z | dmckee - | |
| nan | 110424T205928Z | Joey Ada |
Overload functions (unportable)
Instead of declaring multiple functions...
d(x){return x*2;}
float r(float x){return 1/sqrt(x);}
...
printf( "%d %f\n", d(2), r(2) );
...declare one "function" that does different things depending on return and parameter types.
(*f)()="\x8d\4?\xfR\xc0Ã"; // global
...
printf( "%d %f\n", f(2), ((float(*)(float))f)(2) );
This works because some ABI's (Linux x86_64, in this example) use separate registers for floating point and integer arguments and return values.
The disassembly of the (*f)() "function"...
0: 8d 04 3f lea (%rdi,%rdi,1),%eax
3: 0f 52 c0 rsqrtps %xmm0,%xmm0
6: c3 retq
On a x86_64 Linux machine, this function takes the first integer parameter, doubles it and places the result in %eax (char/short/int/long return value). It takes the first floating point parameter, computes a low precision reciprocal square root and places it in %xmm0 (float/double return value).
Thanks to @PeterCordes for recommending rsqrtps instead of rsqrtss.
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 expressions are all executed
else
printf("failed\n");
}
Outputs: 1 2
If you have some variables declared in a row :
int a,b,c,d;
You can access b by (&a)[1], or c by (&a)[2] ...
It can be interesting there :
i?a=k:i-1?b=k:i-2?c=k:(d=k);
VS
(&a)[i]=k;
You could have declared an array a[4], but if you use a, b, c, d in other ways, it's not always interesting to replace b by a[1], c by a[2]
Moreover, you know that x[y] = *(x+y) = y[x], so :
i?a=k:i-1?b=k:i-2?c=k:(d=k);
VS
(&a)[i]=k;
VS
i[&a]=k;
Abuse implicit conversions
If you need to check if a variable is in a given range (say islower(3))...
Instead of
96<c&c<123
... try something like
c-97<26u // this also has the advantage of only using the expression `c` once
Omit Array Length
If you don't mind possible undefined behavior, define an array C[] (compiler assumes to have one element) and then rely upon the adjacent memory as usable space.
C[];main(){...}
Use strings as arrays
Suppose you had an array like the following.
c[]={1,2,3,4,5,6,7,8,9,10};
// ...some code here...
printf("%d",c[i]);
You can make this at least 9 bytes shorter using this method.
char*x,*c="abcdefghij"; // initialize like this if you already have a 'char *' declaration somewhere.
c[]=L"abcdefghij"; // initialize like this you do not (thanks to @ceilingcat for teaching me this one).
// ...some code here...
printf("%d",c[i]-97);
You can also do something similar with an array of strings.
char*c[]={"cat","dog","mouse","fish"};
// ...some code here...
puts(c[i]);
you can reduce 2 bytes. However, this is slightly more tricker to get right. This usually only works when the length of the strings in the array only differ by 2 at most.
The '.' characters are padding that allows you to access each "substring" within the string using a multiple of a fixed offset.
char*c="cat\0..dog\0..mouse\0fish";
// ...some code here...
puts(c+6*i);
If the order of the strings do not matter, it is best to place the longest string at the end as, you may be able to save some bytes worth of padding.
char*c="cat\0.dog\0.fish\0mouse";
// ...some code here...
puts(c+5*i);
This is a useful trick that I have used to reduce quite a lot of bytes in the following answers.
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 wrote a bash script that may assist in the writing of simple "lambda" functions.
Edit: This technique was previously published by Shinichiro Hamaji in this document.
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.
Conditional printf different format
x>0?printf("%c",x):printf("%d",-x);
printf(x>0?"%c":"%.f",x,0.-x); // float goes different registers
Used here
Use bitwise operators for boolean conditions
For example:
if(a||b) /* do something */
This saves one byte:
if(a|b) /* do something */
Respectively, a!=b becomes a^b and a&&b becomes a&b
An example of using this trick.
Note that sometimes you have to use ||. For example:
if(!a)b++
can be written as
a||b++
but
a|b++
doesn't work.
Calculating \$\lceil\log_{10}(n)\rceil\$
Especially in challenges where properties of decimal representations are of interest, one needs to find a number's decimal representation's length, or for \$n\in\mathbb{N}^+\$ equivalently, \$\lceil\log_{10}(n)\rceil\$.
In this post, several approaches are presented and discussed.
For a C source file containing approaches (a.1) to (b.3) together with a testing setup, see TIO.
I wrote this tip based on this answer of mine, searching for a smaller approach than (a.1).
If you know of any other approach possibly shorter in even a specific scenario, feel free to either add your own tip add to the list below.
(a.1) An expression in n, 20 bytes
snprintf(0,0,"%d",n)
Versatility is a great property of the above approach, when used to determine a number's decimal representation's length, the most direct approach might be the most byte-effective.
0 is given its correct decimal representation length of 1.
GCC only throws a warning for ignoring #include <stdio.h>, otherwise the inclusion would be very byte-heavy at potentially 19+20=39 bytes. If instead of sprintf(0, one uses sprintf(NULL, the byte count is increased to 23 bytes. If using both, the byte count could jump to 42 bytes.
(a.2) A function in n, 29 bytes
a(n){n=snprintf(0,0,"%d",n);}
By being a function, this approach's versatility is high; (a.1)'s compiler-specifics also apply, when properly returning, the byte count increases to 5+29=34 bytes.
0 is given its correct decimal representation length of 1.
(b.1) A function in n, requiring another variable, 32 bytes
b(n,k){for(k=0;n;k++)n/=10;n=k;}
Of all approaches presented, this one has the worst byte count. However, considering potential compiler restrictions discussed in (a.1), it could prove more byte-efficient, since the approach is nearer to the C core.
0 is given its incorrect decimal representation length of 0. One can make the case for defining \$\lceil-\infty\rceil:=0\$ which would make this approach closer to a logarithm implementation, when further defining \$\log(0):=-\infty\$.
Modification to calculate \$\lceil\log_b(n)\rceil\$ for a base \$b\in\mathbb{N}^+\$ is possible, changing the byte count by the bytes required to represent \$b\$ in C-source.
(b.2) A statement requiring existence of two variables, setting n=0, 20 bytes
for(k=0;n;k++)n/=10;
If another variable is already declared and n can be either discarded or needs to be cleared regardless and the use case is a whole block instead of a one-line expression, the above could be used. Since it is equivalent in byte count to (a.1), the behavioural differences have to be analyzed.
Minimally wrapped inside a function, it becomes (b.1), both being similar in features.
(b.3) A statement working additively on k, setting n=0, 17 (pot. 16) bytes
for(;n;k++)n/=10;
Another variation on (b.1), removing initialization of k. Furthermore, for(; leaves space for an expression, potentially allowing to save a semicolon's byte, effectively rendering this approach 16 bytes long.
(c.1) A statement in n, producing stdout-output, 14 bytes
printf("%d",n)
Courtesy of H.PWiz.
This approach's utter conciseness and simplicity may be alluring, its major drawback, however, is its stdout-output; tolerability being heavily challenge-dependent.
(c.2) A statement in n, producing stderr-output, 17 bytes
dprintf(2,"%d",n)
Courtesy of Jo King.
The above is equivalent to the five bytes longer fprintf(stderr,"%d",n) and a variant of (c.1), side-effecting not stdout but rather the much more clutterable stderr.
Ref. man dprintf.3
Abuse wchar_t to print one character from a string
In a little-endian architecture, you can replace
putchar("string"[i])
with
printf(L"string"+i)
to save a byte.
Use bitwise operators to convert characters to uppercase/lowercase. Bitwise AND with 95 (or '_') to convert to uppercase, bitwise OR with 32 (or ' ') to convert to lowercase, and to invert case, bitwise XOR with 32 (or ' ').
This only works for letters, and it also seems to work for just a few other characters: { and } are lowercase for [ and ], ~ and ` are lowercase for ^ and @, ) is lowercase for a tab, and * is lowercase for a newline.
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.
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);
Sometimes you can use floating point where you don't expect to.
Ignoring possible floating point imprecision issues you still can use them with many operators you wouldn't normally expect :
++--increment / decrement!||&&Boolean comparative?and even ternary!
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.
Omit return
Surprised that only this answer provided a similar situation
Instead of return x; in the end, use g=x; where g is a global variable.
In other situations, it may be more shortened. Refer here for more about this.
instead of the printf loop
for(i=1;i<12;i++){if(!i%3)printf("\n");printf("%d",i);}
just use
for(i=1;i<12;i++) printf("%c%d",!(i%3)*10,i);
it helps me so much .
@SamHocevar 's answer (shorter by 2bytes)
for(i=1;i<12;i++) printf("\n%d"+!!(i%3),i);
Credits to @AbhayAravinda for ripping off three more bytes
for(i=1;i++<12;) printf("\n%d"+!!(i%3),i);
The incrementer here works as a part of the inspector.
Favor recursion over loops, especially if going forwards then backwards
Loops, 67 bytes
l;f(char*s){for(l=0;s[l];)putchar(s[l++]);for(;l;)putchar(s[--l]);}
Recursion, 47 bytes
f(char*s){*s?putchar(*s),f(s+1),putchar(*s):0;}
You can remove two for-loops and a counter variable. Even if you use just one for-loop in order to loop in one direction, you could save ~10 bytes with this transformation.
Abuse two's complement
A lot of expressions can be changed by (ab)using two's complement. Take this for example:
getchar()+1
If you need higher precedence, you can use this:
-~getchar()
Or, if you're using it as the condition for a loop, this can be used:
~getchar()
Additionally, instead of subtracting one after another subtraction:
a+b-1
you can add the bitwise-NOT of the second operand:
a+~b
This applies similarly to multiplication by 2:
2*(a-b)-1
can be shortened to:
a-b+a+~b
Exploit ASLR
On systems with ASLR (Address Space Layout Randomization), the address of a stack variable can be used as a one time pseudorandom number. Instead of something like...
srand(time(0));
...try something like
srand(&x)
...where the address of x (hopefully on the stack) is unique each time the program is run.
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);.
Try cpow() instead of cos()
Instead of
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.
Get the length of a string with puts() instead of strlen()
According to the standard C specification, puts() returns a non-negative integer on success. In practice, most C libraries seem to treat puts(s) as equivalent to printf("%s\n", s), which returns an integer equal to the number of bytes written.
As a result, the return value of puts(s) is equal to 1 + strlen(s). If the additional console output can be ignored, this saves a few bytes.
Boolean constant string selection when the selector's true value is guaranteed to be one larger than the second option's length
At its heart, this tip attempts to golf a ternary if of the form cnd?str_true:string_false when two conditions are met, namely that both str_true and string_false are constant strings and cnd is either 0 or strlen(string_false)+1.
If the above conditions are met, the expression cnd?"true":"false" can be golfed* by one byte to "false\0true"+cnd (here cnd == 0 || cnd == 6 always holds); another byte can be shaved off by not escaping the null byte (a compiler dependent feature).
The tip in action
For this example, suppose the string selection's criterion is k%3's truthiness, where k-1 is never divisible by three. In this case the ternary if
k%3?"°@°":"_" // 13 bytes
can be golfed to:
"_\0°@°"+k%3 // 12 bytes
Which can be golfed down to eleven bytes if one does not escape the null byte.
Application in obfuscation
As the above requirements are rather strict, this tip is most likely not widely applicable. Nonetheless, the shown technique can also be used to potentially obfuscate a program at no further byte cost.
Given e as a truly boolean expression -- (e) == 0 || (e) == 1 holds -- with the proper operator precedence regarding the upcoming factor, the following snippets are interchangeable* at the same byte count -- when not escaping the null byte.
e?"lifeless":"lychee"
"lychee\0lifeless"+e*7
Bare in mind that this obfuscation is only non-detrimental to the byte count if the second option's string is not longer than eight characters -- since else the factor spans more than one byte.
*: If interpreted as constant strings.
Use recursion over loops.
Recursive example
f(){printf("infiniteloop");f();}
For loop equivalent is 3 bytes longer.
f(){for(;;)printf("infiniteloop");}
When your algorithm produces output in reverse order, take a pointer to the end of a buffer and write it in decreasing order, returning a pointer to the first element. It's up to the caller to supply a buffer large enough for any this input, or for any possible input.
Base conversion / int-to-string is a classic example where this interface is used in real life, such as glibc's internal _itoa, used by the printf family of functions as well as some other internal callers. The max buffer size is 65 bytes for a 64-bit integer -> base 2 string.
// takes a pointer to one-past-the-end, which is also a valid option.
char *itoa_end(unsigned long val, char *p_end) {
// does *not* zero terminate the buffer. Use *--p_end = 0;
const unsigned base = 10;
char *p = p_end;
do {
*--p = (val % base) + '0';
val /= base;
} while(val); // runs at least once to print '0' for val=0.
// write(1, p, p_end-p);
return p; // let the caller know where the leading digit is
}
For golfing, it can be more compact to take the pointer by reference and modify it, instead of returning it. (return is a long keyword, and code depending on gcc -O0 evaluating expressions in the return-value register isn't even C.)
For example, I used this in ASCII art uncompression from a base-n number (i.e. int->string with a digit lookup table), where I already needed a char* arg, so it was very cheap to declare another as a char **.
Use *p everywhere you have p in the simple version. *--*p decrements the caller's pointer, then dereferences that to reference the actual character.
/* int n = the number
* int B = size of I = base
* char I[] = input table
* char **O = input/output arg passed by ref:
* on entry: pointer to the last byte of output buffer.
* on exit: pointer to the first byte of the 0-terminated string in output buffer
*/
void semi_golfed_g(n,I,B,O)char*I,**O;
{
for(**O=0 ; n ; n/=B)
*--*O = I[n%B];
}
Set an array of int to the same value (C99, Linux, BSD, OSX)
Instead of
int a[n]=...,x=...;
for(int i=n;i--;)a[i]=x
Try something like
int a[n]=...,x=...;
wmemset(a,x,n);
On MSVC on Windows, wmemset() works on arrays of short instead of int.
Inverse flag update
Sometimes a challenge asks to determine a data set's specific boolean property. To avoid the unacceptably long return keyword, I often use a flag variable which gets updated in a loop and assign-returned at the end (I will refer to this tip for more detail on assign-returning).
When working with such boolean flags and boolean values, to update them I often use either f&=a|b or f*=a|b to align them with the result of a|b. This is equivalent to saying f = f && (a|b).
However, sometimes a flag needs to be inversely updated, meaning f = f && !(a|b). Naively, one would use f&=!(a|b) (9 bytes), or -- using fundamental logical equivalences -- one would golf it to f&=!a&!b (8 bytes).
For the case of an inverse flag update, though, one might be better off using the binary shift right operator >>, as the previous assignment is (when working with boolean values) equivalent to f>>=!(!a&!b), which simply golfs to f>>=a|b (7 bytes).
If the flag update in question does not involve parentheses due to negation (as in the previous example), inverse flag updating may still be shorter, as for example f&=!a|!b (8 bytes) is equivalent to f&=!(a&b) (9 bytes), which is equivalent to f>>=a&b (7 bytes).
Inverse flag updating may in certain cases also be used even though the values in question are not boolean (either 0 or 1).
If only one operand is boolean, bitwise and (&) can still be used, as the second operand's bits will all be cleared. When using bitwise or (|) or both operands are non-boolean, one should consider using logical and (&&) and logical or (||) to get a boolean result, even though they are one byte longer.
As a side node, these rules also apply when the expression is side-effect-dependent, meaning !f()&&!g() is equivalent to !(f()||g()) regarding the execution of g(), such that even in those cases inverse flag updating can be used.
For testing purposes, I wrote a simple truth table tester (TIO-link).
One recent real-world example of this technique in action would be for example my answer to Detect Rectangular Text.
Sometimes, albeit rarely, if your code contains many for loops, #define F for( may save a byte or two (especially if some of the loops have an empty init section).
If it is applicable to your situation, #define F;for( may save even more bytes.
Examples:
Whenever a certain function is called several times, it's common to #define it to something shorter. However, certain compilers (MinGW and clang as far as I know) allows for something even more compact by using function pointers:
(*P)()=printf;
P("Test: %d\n", 10);
Other compilers might require an #include of the proper header file for it to work.
Inline arrays
If you need a non-int constant array and just use it once, you can do
float f(a){return (float[]){.3,.2,.7}[a];}
instead of
float z[]={.3,.2,.7};float f(a){return z[a];}
to save 3 bytes.
(In this case it can save one more byte since the blank after return can be omitted.)
import if you have to
As noted in the very first answer, some compilers (notably, GCC and clang) let you get away with omitting #includes for standard library functions.
Even if you can't just remove the #include, there might be other ways to avoid it, but that's not always practical or particularly golfy.
In the remaining cases, you can use #import<header file> instead of #include<header file> to save a byte. This is a GNU extension and it is considered deprecated, but it works at least in gcc 4.8, gcc 5.1, and clang 3.7.
Use s[i] instead of i<strlen(s) in string-handling loops
For example:
for(i=0;i<strlen(s);i++)s[i]=s[i+1];
can be shortened to:
for(i=0;s[i];i++)s[i]=s[i+1];
Use #define instead of functions when possible
For example:
f(int i,char*s){/*do something with i and s*/;}
Using #define can eliminate the argument list type, curly-braces and closing semicolon:
#define f(i,s)/*do something with i and s*/
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:
Swap variables
If you ever need to swap variables, don't use the pattern with an extra variable or that addition-subtraction-method, just do some chained XORing:
a^=b^=a^=b;
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
-m32flag (gcc). This costs 0 bytes.
Reverse Loops
If you can, try to replace
for(int i=0;i<n;i++){...}
with
for(int i=n;i--;){...}
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;}
When you have to walk a string you can walk the pointer instead of incrementing the index.
Code :
#include <stdio.h>
// print each char
void f(char* s) {
for (int i=0;s[i];i++) putchar(s[i]);
}
// same output than f;
void g(char* s)
{
for (;*s;) putchar(*s++);
}
int main(void) {
f("hello\n");
g("hello\n");
return 0;
}
example: Remove duplicated & switched case
Knowing basic logical equalities might be able to save a couple bytes. For instance, instead of if (!(a&&b)){} try instead using DeMorgan's law if (!a||!b){}. The same applies to bitwise functions: instead of ~(a|b) do ~a&~b.
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
Here are a few tips I've used to my advantage. I've shamelessly stolen them from others, so credit to anyone but me:
Combine assignment with function calls
Instead of this:
r = /* Some random expression */
printf("%d", r);
Do this:
printf("%d", r = /* Some random expression */);
Initialize multiple variables together (when possible)
Instead of this:
for(i=0,j=0;...;...){ /* ... */ }
Do this:
for(i=j=0;...;...){ /* ... */ }
Collapse zero/nonzero values
This is a neat trick I picked up from someone here (don't remember who, sorry). When you have an integer value and you need to collapse it to either 1 or 0, you can use !! to do so easily. This is sometimes advantageous for other alternatives like ?:.
Take this situation:
n=2*n+isupper(s[j])?1:0; /* 24 */
You could instead do this:
n=n*2+!!isupper(s[j]); /* 22 */
Another example:
r=R+(memcmp(b+6,"---",3)?R:0); /* 30 */
Could be rewritten as:
r=R+R*!!memcmp(b+6,"---",3)); /* 29 */
For scanning a string into an array, you can use
gets(str);
instead of
scanf("%s",str);
Use bitwise and (&) when comparing boolean expressions to save one byte.
Example:
if(i^2&k/3) DoSomething;
Really, really useful when combined with the other tips
If you ever need to output a single newline character (\n), don't use putchar(10), use puts("").
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.
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.
Use
*ainstead ofa[0]for accessing the first element of an array.Relational operators (
!=,>, etc.) give0or1. Use this with arithmetic operators to give different offsets depending on whether the condition is true or false:a[1+2*(i<3)]would accessa[1]ifi >= 3anda[3]otherwise.
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.
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 */
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
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);
}
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);
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.
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
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 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.
use
scanf("%*d ");to read the dummy input. (in case that input is meaningless in further program) it is shorter thanscanf("%d",&t);where you also need to declare the variable t.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]);}
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.
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.
Use bitwise XOR to check for inequality between integers:
if(a^b) instead of if(a!=b) saves 1 character.
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.
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 as1, 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!)
