Why does a function with no parameters (compared to the actual function definition) compile?

AdmiralJonB picture AdmiralJonB · Dec 19, 2012 · Viewed 59.7k times · Source

I've just come across someone's C code that I'm confused as to why it is compiling. There are two points I don't understand.

First, the function prototype has no parameters compared to the actual function definition. Second, the parameter in the function definition does not have a type.

#include <stdio.h>

int func();

int func(param)
{
    return param;
}

int main()
{
    int bla = func(10);    
    printf("%d", bla);
}

Why does this work? I have tested it in a couple of compilers, and it works fine.

Answer

Krishnabhadra picture Krishnabhadra · Dec 19, 2012

All the other answers are correct, but just for completion

A function is declared in the following manner:

  return-type function-name(parameter-list,...) { body... }

return-type is the variable type that the function returns. This can not be an array type or a function type. If not given, then int is assumed.

function-name is the name of the function.

parameter-list is the list of parameters that the function takes separated by commas. If no parameters are given, then the function does not take any and should be defined with an empty set of parenthesis or with the keyword void. If no variable type is in front of a variable in the paramater list, then int is assumed. Arrays and functions are not passed to functions, but are automatically converted to pointers. If the list is terminated with an ellipsis (,...), then there is no set number of parameters. Note: the header stdarg.h can be used to access arguments when using an ellipsis.

And again for the sake of completeness. From C11 specification 6:11:6 (page: 179)

The use of function declarators with empty parentheses (not prototype-format parameter type declarators) is an obsolescent feature.