20

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?!

Null
  • 1,950
  • 9
  • 30
  • 33
Zaffy
  • 16,801
  • 8
  • 50
  • 77
  • 1
    possible duplicate of [C void arguments](http://stackoverflow.com/questions/693788/c-void-arguments) – Paul R Jul 25 '12 at 09:15

2 Answers2

28

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

Paul R
  • 208,748
  • 37
  • 389
  • 560
15
 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);
ouah
  • 142,963
  • 15
  • 272
  • 331
  • I always forget C does that! Even if it was `int test(void);` but cross TU there's no requirement for a diagnostic to be issued though. – Flexo Jul 25 '12 at 09:09