6

I was trying to declare a function pointer that points to any function that returns the same type. I omitted the arguments types in the pointer declaration to see what error will be generated. But the program was compiled successfully and executed without any issue.

Is this a correct declaration? Shouldn't we specify the arguments types?

#include <stdio.h>
#include <stdlib.h>

void add(int a, int b)
{
    printf("a + b = %d", a + b);
}

void (*pointer)() = &add;

int main()
{
    add(5, 5);
    return 0;
}

Output:

a + b = 10
BenMorel
  • 34,448
  • 50
  • 182
  • 322
rullof
  • 7,124
  • 6
  • 27
  • 36

3 Answers3

7

Empty parentheses within a type name means unspecified arguments. Note that this is an obsolescent feature.

C11(ISO/IEC 9899:201x) §6.11.6 Function declarators

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

Community
  • 1
  • 1
Yu Hao
  • 119,891
  • 44
  • 235
  • 294
6

void (*pointer)() explains function pointed have unspecified number of argument. It is not similar to void (*pointer)(void). So later when you used two arguments that fits successfully according to definition.

Dayal rai
  • 6,548
  • 22
  • 29
0

There are couple of things you should know here...

Function declaration:

int myFunction();

Function prototype:

int myFunction(int a, float b);
  • A prototype is a special kind of declaration that describes the number and the types of function parameters.
  • A non-prototype function declaration doesn't say anything about its parameter.

Example:

int myFunction();

This non-prototype function declaration does not mean that myFunction takes no arguments. It means that myFunction take an unspecified number of arguments. The compiler simply turns off argument type checking, number of arguments checking and conversion for myFunction.

So you can do,

int myFunction();   // The non-prototype signature will match a definition for
                    // myFunction with any parameter list.
// This is the function definition... 
int myFunction(int x, float b, double d)
{
    ...
}
  • 1
    `float` becomes `double` after promotion. You cannot use non-prototype declarations if you use non-fully-promoted argument types. – mafso Dec 30 '13 at 10:00