Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can c declare two function with the same name, return type but different parameters

Tags:

c

gcc

Why the following code can be compiled by gcc

#include <stdio.h>
int func();
int func(int a) { return 1; }
int main() {
   func(10);
   return 0;
}

But if i add char func();, gcc say conflicting types for ‘func’

like image 361
Steve Avatar asked Dec 13 '22 22:12

Steve


2 Answers

This is not an overload, because you cannot call func() with no arguments. This is a special case of a single function with compatible function declarators, as described in the standard:

If one type has a parameter type list and the other type is specified by a function declarator that is not part of a function definition and that contains an empty identifier list, the parameter list shall not have an ellipsis terminator and the type of each parameter shall be compatible with the type that results from the application of the default argument promotions.

Changing return type from int to char is one way to break this rule. Another way to break it is to supply a parameter type other than int:

int func();
int func(char a) { return 1; } // Does not compile

If you would like to declare a function that does not take any parameters, the declarator should be as follows:

int func(void);

Now declaring a func that takes an int will result in compile-time error:

int func(void);
int func(int a) { return 1; } // Does not compile
like image 145
Sergey Kalinichenko Avatar answered Jan 22 '23 14:01

Sergey Kalinichenko


Your first declaration is K&R declaration, while the next declaration (with definition) is ANSI prototype.

It is possible to make any combination between KR decl and ANSI prototypes, if they are compatible .

The C type checker will combine both and will keep the ANSI prototype. This is called the composite type.

Here is how the composite type is computed for the combination between ANSI and K&R decl:

6.2.7 Compatible type and composite type

3 ... If only one type is a function type with a parameter type list (a function prototype), the composite type is a function prototype with the parameter type list.

To check whether 2 function declarations are compatible one must apply the rules from 6.7.6.3 Function declarators

15 For two function types to be compatible, both shall specify compatible return types.146) Moreover, the parameter type lists, if both are present, shall agree in the number of parameters and in use of the ellipsis terminator; corresponding parameters shall have compatible types.

This is why your prototype can be combined with K&R decl, as they are considered compatibles.

like image 34
alinsoar Avatar answered Jan 22 '23 15:01

alinsoar