Dmitry Belyavsky (beldmit) wrote,
Dmitry Belyavsky

Сеанс чёрной магии

Как поменять порядок аргументов, передаваемых в функцию, особо извращённым способом. И почему это работает.

#include <math.h>
#include <stdio.h>

double DoubleToTheInt(double base, int power) {
return pow(base, power);

int main() {
// cast to a function pointer with arguments reversed
double (*IntPowerOfDouble)(int, double) =
(double (*)(int, double))&DoubleToTheInt;

printf("(0.99)^100: %lf \n", DoubleToTheInt(0.99, 100));
printf("(0.99)^100: %lf \n", IntPowerOfDouble(100, 0.99));
The code above never actually defines the function IntPowerOfDouble — because there is no function IntPowerOfDouble. It's a variable that points to DoubleToTheInt, but with a type that says it likes its integer arguments to come before its doubles.

You might expect the IntPowerOfDouble to take its arguments in the same order as DoubleToTheInt, but cast the arguments to a different type, or something like that. But that's not what happens.

Try it out — you'll see the same result value printed on both lines.

emiller@gibbon ~> clang something.c
emiller@gibbon ~> ./a.out
(0.99)^100: 0.366032
(0.99)^100: 0.366032

Программиста, который такие трюки применяет, надо расстреливать увольнять.

This entry was originally posted at Your comment? (comment count unavailable comments)
Tags: программирование, ссылки
  • Post a new comment


    Anonymous comments are disabled in this journal

    default userpic

    Your reply will be screened

    Your IP address will be recorded