Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we modify function prototype inside function?

Tags:

c

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?

like image 655
sanket babar Avatar asked Sep 07 '17 09:09

sanket babar


2 Answers

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

like image 29
Spektre Avatar answered Sep 27 '22 16:09

Spektre