通过函数指针传递其他参数是否合法/已在C中定义? [英] Is passing additional parameters through function pointer legal/defined in C?

查看:88
本文介绍了通过函数指针传递其他参数是否合法/已在C中定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
将函数指针投射到另一种类型

Possible Duplicate:
Casting a function pointer to another type

假设我使用一个实际上需要比参数指针定义少的参数的函数来初始化一个函数指针,如果通过函数指针调用该函数是否仍能正确执行?

Assume i initialize a function pointer with a function that actually takes less parameters then the function pointer definition, will the function still perform correctly if called through the function pointer?

我在gcc上尝试了此操作,并且按预期方式工作,但我想知道这种行为在编译器/平台之间是否一致(我怀疑在某些环境下它可能会对堆栈造成严重破坏):

I tried this with gcc and it worked as expected, but i wonder if that behaviour is consistent across compilers/platforms (i suspect in some enviroments it might wreak havoc on the stack):

#include <stdio.h>

typedef void (*myfun)(int, int, int);

void test_a(int x, int y, int z) {
    printf("test_a %d %d %d\n", x, y, z);
}

void test_b(int x, int y) {
    printf("test_b %d %d\n", x, y);
}

int main() {
    myfun fp;
    fp = test_a;
    fp(1, 2, 3);
    fp = (myfun) test_b;
    fp(4, 5, 6);
}

推荐答案

程序的行为未定义.它完全可以编译的事实是由于强制转换,它有效地告诉编译器这是错误的,但无论如何还是要这样做".如果删除演员表,则会收到相应的错误消息:

The behavior of your program is undefined. The fact that it compiles at all is because of the cast, which effectively tells the compiler "this is wrong, but do it anyway". If you remove the cast, you'll get the appropriate error message:

a.c:17:8: error: assignment from incompatible pointer type [-Werror]

(来自gcc -Wall -Werror.)

更具体地说,行为取决于调用约定.如果您在平台上,参数是按反向"顺序在堆栈上传递的,则程序将给出非常不同的结果.

More specifically, the behavior depends on the calling conventions. If you were on a platform were the arguments were passed in "reverse" order on the stack, the program would give a very different result.

这篇关于通过函数指针传递其他参数是否合法/已在C中定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆