Quantcast
Viewing latest article 28
Browse Latest Browse All 67

Answer by ceilingcat for Tips for golfing in C

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)()=L"\xf33f048d\xc3c0520f"; // global...printf( "%d %f\n", f(2), ((float(*)(float))f)(2) );

Try it online! 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),%eax3:       f3 0f 52 c0             rsqrtss %xmm0,%xmm07:       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).


Viewing latest article 28
Browse Latest Browse All 67

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>