3

The source code example is:

int add2(int a0, int a1)
{
    return a0+a1;
}

int add4(int a0, int a1, int a2, int a3)
{
    return a0+a1+a2+a3;
}

int (*fptr)(int a0,int a1,int a2,int a3,int a4,int a5,int a6,int a7);

int main()
{
    volatile int ret0;
    int a0=0;
    int a1=1;
    int a2=2;
    int a3=3;
    int a4=4;
    int a5=5;
    int a6=6;
    int a7=7;

    fptr = add4;
    ret0=fptr(a0,a1,a2,a3,a4,a5,a6,a7);

    return ret0;
}

In this example we have function pointer with 8 arguments. I'am assigning to this pointer the pointer of the function which contains 4 arguments. In this case, compiler may generate assembly code, which will use stack and registers, which are not used in the target function (with 4 arguments). Is it legal to assign and use address of function which has less arguments than the function pointer? Is it safe to use such a programming pattern?

lol lol
  • 319
  • 3
  • 18

2 Answers2

3

The assignment is valid:

fptr = add4;

C17::6.3.2.3::8:

A pointer to a function of one type may be converted to a pointer to a function of another type and back again; the result shall compare equal to the original pointer. If a converted pointer is used to call a function whose type is not compatible with the referenced type, the behavior is undefined.

However, it's only valid to store it as a different function pointer, and not valid to use it (actually call the function):

ret0 = fptr(a0, a1, a2, a3, a4, a5, a6, a7);

C17::6.5.2.2::Constraints.2:

If the expression that denotes the called function has a type that includes a prototype, the number of arguments shall agree with the number of parameters. Each argument shall have a type such that its value may be assigned to an object with the unqualified version of the type of its corresponding parameter.

Links: Where do I find the current C or C++ standard documents?

2

Is it legal to assign and use address of function which has less arguments than the function pointer?

No, the function pointer should have the same type and number of arguments as the underlying function.

Ref http://port70.net/~nsz/c/c99/n1256.html#6.5.16.1

The following constraints shall hold for simple assignment

  • ...
  • both operands are pointers to qualified or unqualified versions of compatible types, and the type pointed to by the left has all the qualifiers of the type pointed to by the right;
  • ..
Rishikesh Raje
  • 8,556
  • 2
  • 16
  • 31
  • 2
    No. The Undefined Behaviour is in the call; the assignment is valid: **C17::6.3.2.3::8:** *"A pointer to a function of one type may be converted to a pointer to a function of another type and back again; the result shall compare equal to the original pointer. If a converted pointer is used to call a function whose type is not compatible with the referenced type, the behavior is undefined."* – alx - recommends codidact Jul 15 '19 at 12:38