Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why prototype and definition of a function in C may differ?

Tags:

I'm wondering why this will compile:

int test();

int main() { return test((void*)0x1234); }
int test(void* data) { return 0; }

Why won't the compiler emit any error/warning about that (I tried clang, gcc)? If I change the return value it won't compile - but the arguments may differ?!

like image 648
Zaffy Avatar asked Jul 25 '12 09:07

Zaffy


People also ask

How does a function prototype differ from a function definition?

While a function definition specifies how the function does what it does (the "implementation"), a function prototype merely specifies its interface, i.e. what data types go in and come out of it.

Is function prototype and function declaration same?

A function declaration is any form of line declaring a function and ending with ; . A prototype is a function declaration where all types of the parameters are specified.

How is a function prototype different than a function header?

The only difference between the function prototype and the function header is a semicolon (see diagram below). The function definition is placed AFTER the end of the int main(void) function. The function definition consists of the function header and its body.

What are different function prototypes in 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

If you change:

int test();

to:

int test(void);

you will get the expected error:

foo.c:4: error: conflicting types for ‘test’
foo.c:1: error: previous declaration of ‘test’ was here

This is because int test(); simply declares a function which takes any parameters (and is therefore compatible with your subsequent definition of test), whereas int test(void); is an actual function prototype which declares a function which takes no parameters (and which is not compatible with the subsequent definition).

like image 105
Paul R Avatar answered Sep 20 '22 08:09

Paul R


 int test();

in a function declaration, no parameter means the function takes an unspecified number of arguments.

This is different than

 int test(void);

which means the function takes no argument.

A function declaration with no parameter is the old C style of function declaration; C marks this style as obsolescent and discourages its use. In short, don't use it.

In your case, you should use a function declaration with the correct parameter declaration:

 int test(void *data);
like image 25
ouah Avatar answered Sep 21 '22 08:09

ouah