Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function pointers assignment

Following the question Function pointer in Visual Studio 2012 I've started to wonder about the legality of certain assignments to function pointers in C.

The code below compiles with a warning, like I would expect because the assigned function requires more parameters than the function pointer declaration describes (GCC 4.8):

#include <stdio.h>

int test(int x, int y)
{
    printf("%d", x);
    printf("%d", y);
    return 0;
}

int main()
{
    int (*test_ptr)(int);
    test_ptr = test;
    test_ptr(1);
    return 0;
}

Same warning appears if changing the code so that assigned function requires less parameters (GCC 4.8). Again, this is expected.

However, the following code compiles without a single warning, although the assigned function needs 2 parameters instead of 0 (GCC 4.8):

#include <stdio.h>

int test(int x, int y)
{
    printf("%d", x);
    printf("%d", y);
    return 0;
}

int main()
{
    int (*test_ptr)();
    test_ptr = test;
    test_ptr();
    return 0;
}

No castings are involved anywhere.

Can anyone explain this compiler behavior?

like image 993
SomeWittyUsername Avatar asked Dec 21 '22 08:12

SomeWittyUsername


1 Answers

The following:

int (*test_ptr)();

takes an unspecified number of parameters, not zero parameters.

For the latter, write

int (*test_ptr)(void);

P.S. Calling a two-argument function with zero arguments leads to undefined behaviour.

like image 52
NPE Avatar answered Jan 02 '23 10:01

NPE