简体   繁体   English

我们可以在函数内修改函数原型吗?

[英]Can we modify function prototype inside function?

I am having declaration in C as follows : 我在C中声明如下:

void abcd(int , char);

void main()
{
    extern void abcd(char);
    abcd (q);
}

Is it okay to have such code implemented? 是否可以实现这样的代码? How C will allow us to code like this? C将如何允许我们这样编码? function call to abcd() will take 'q' as a char or as an integer? 函数调用abcd()会将'q'作为char还是整数?

C11 6.2.7p2 C11 6.2.7p2

All declarations that refer to the same object or function shall have compatible type ; 引用同一对象或函数的所有声明都应具有兼容类型 ; otherwise, the behavior is undefined . 否则, 行为未定义

void abcd(int, char); is an external declaration that says abcd takes int and char as arguments. 是一个外部声明,表示abcdintchar作为参数。 It is not compatible with extern void abcd(char); 它与extern void abcd(char);不兼容extern void abcd(char); , which says that the same function now takes just one char as an argument. ,它说同一个函数现在只需要一个char作为参数。

If I read the standard correctly, this is not a constraint error, so a compiler need not produce even a warning for this. 如果我正确读取标准,这不是约束错误,因此编译器甚至不需要为此生成警告 It is still broken and wrong. 它仍然是破碎和错误的。

sorry I overlooked the C instead C++ tag (C++ stuff removed). 对不起,我忽略了C而不是C ++标签(删除了C ++的东西)。 I think this should do in C: 我认为这应该在C中做:

void abcd_c(char x){};
void abcd_i(int x){};
int main(int argc, char *argv[])
 {
 #define abcd abcd_c
 abcd('t');
 abcd('e');
 abcd('s');
 abcd('t');
 #undef abcd

 #define abcd abcd_i
 abcd(123);
 #undef abcd
 }

You just use #define/#undef to select wanted behavior in parts of code 您只需使用#define/#undef在部分代码中选择想要的行为

I believe that in C you cannot do this. 我相信在C中你不能这样做。 Actually the compiler will not even bother to "cry" as this is syntactically correct. 实际上编译器甚至都不会“哭”,因为这在语法上是正确的。 But on the other hand this is wrong and won't execute. 但另一方面,这是错误的,不会执行。 Personally I pay very much attention at mistakes that compiler accepts but disrupts the execution. 就个人而言,我非常关注编译器接受的错误但会破坏执行。 Generally speaking you have to declare this function above main , with the proper argument , character in this situation. 一般来说,在这种情况下,您必须使用正确的参数,字符在main之上声明此函数。 Because C will look for the declaration of this particular function and she won't find it. 因为C会查找这个特定函数的声明,但她找不到它。 In C++ it's easy as you can overload functions and compiler would understand just from the type of arguments. 在C ++中,它很容易,因为你可以重载函数,编译器只能从参数类型中理解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM