学习并弄乱了函数指针,我注意到了一种初始化void函数指针并转换它们的方法.然而,虽然我没有收到任何警告或错误,无论是使用GCC还是VS的编译器,我都想知道这样做是危险的还是坏的做法,因为我没有看到这种方法通常在互联网.而且,我们称之为通用函数指针吗?
#include <stdio.h>
#include <stdint.h>
#include <conio.h>
#define PAUSE (_getch())
uint16_t add(const uint16_t x, const uint16_t y) {
return x + y;
}
char chr(uint8_t test) {
return (char)test;
}
int main(void) {
void(*test)() = (void*)add;
const uint16_t x = 1, y = 1;
uint16_t value = ((uint16_t(*)())test)(x, y);
test = (void*)chr;
printf("%d\n", add(x, y)); // 2
printf("%d\n", value); // 2
printf("%c\n", ((char(*)())test)(100)); // d
PAUSE;
return 0;
}
Run Code Online (Sandbox Code Playgroud) 我试图声明一个指向任何返回相同类型的函数的函数指针.我省略了指针声明中的参数类型,以查看将生成什么错误.但该程序编译成功并执行没有任何问题.
这是正确的声明吗?我们不应该指定参数类型吗?
#include <stdio.h>
#include <stdlib.h>
void add(int a, int b)
{
printf("a + b = %d", a + b);
}
void (*pointer)() = &add;
int main()
{
add(5, 5);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:
a + b = 10
Run Code Online (Sandbox Code Playgroud)