简体   繁体   中英

Can we modify function prototype inside function?

I am having declaration in C as follows :

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? function call to abcd() will take 'q' as a char or as an integer?

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. It is not compatible with extern void abcd(char); , which says that the same function now takes just one char as an argument.

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). I think this should do in 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

I believe that in C you cannot do this. 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. Because C will look for the declaration of this particular function and she won't find it. In C++ it's easy as you can overload functions and compiler would understand just from the type of arguments.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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