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 (llvm 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 quoted string 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
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
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.
9I think the biggest single-sentence hint is: Read the winning codes submitted to IOCCC. – vsz – 2012-05-12T21:23:52.903