I'm using the below code:
char dest[5]; char src[5] = "test"; printf("String: %s\n", do_something(dest, src)); char *do_something(char *dest, const char *src) { return dest; }
The implementation of do_something
is not important here. When I try to compile the above I get these two exception:
error: conflicting types for 'do_something' (at the printf call)
error: previous implicit declaration of 'do_something' was here (at the prototype line)
Why?
Conflicting Types for Error - Is a common mistake in programming it occurs due to incompatibility of parameters/arguments type in declaration and definition of the function. Let's understand by example: In this program we are finding the average of two numbers and we create a user define function name average().
A function prototype is simply the declaration of a function that specifies function's name, parameters and return type. It doesn't contain function body. A function prototype gives information to the compiler that the function may later be used in the program.
You are trying to call do_something before you declare it. You need to add a function prototype before your printf line:
char* do_something(char*, const char*);
Or you need to move the function definition above the printf line. You can't use a function before it is declared.
In "classic" C language (C89/90) when you call an undeclared function, C assumes that it returns an int
and also attempts to derive the types of its parameters from the types of the actual arguments (no, it doesn't assume that it has no parameters, as someone suggested before).
In your specific example the compiler would look at do_something(dest, src)
call and implicitly derive a declaration for do_something
. The latter would look as follows
int do_something(char *, char *)
However, later in the code you explicitly declare do_something
as
char *do_something(char *, const char *)
As you can see, these declarations are different from each other. This is what the compiler doesn't like.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With