Сеанс чёрной магии
Aug. 11th, 2016 03:59 pmКак поменять порядок аргументов, передаваемых в функцию, особо извращённым способом. И почему это работает.
#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
Программиста, который такие трюки применяет, надорасстреливать увольнять.
#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
Программиста, который такие трюки применяет, надо