Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting "conflicting types for function" in C, why?

Tags:

arrays

c

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?

like image 861
goe Avatar asked Oct 11 '09 01:10

goe


People also ask

What is conflicting types in C?

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().

What is a function prototype C?

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.


2 Answers

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.

like image 182
James McNellis Avatar answered Sep 29 '22 21:09

James McNellis


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.

like image 21
AnT Avatar answered Sep 29 '22 23:09

AnT