4

in the following code in file func.c:

#include <stdio.h>

int Myfunc1(int i, int z)
{
    return i;
}

int main()
{
    int ans;

    /*  casting the function into an 'int (int)' function   */
    ans = ((int(*)(int))(Myfunc1))(5);

    printf("ans: %d\n\n", ans);

    return 0;
}

i tried to cast an int(int,int) function into an int(int) function an got the gcc warning and note:

func.c:13:32: warning: function called through a non-compatible type [enabled by default]
func.c:13:32: note: if this code is reached, the program will abort

and when trying to run i get:

Illegal instruction (core dumped)

but if i compile this file with a .cpp ending with the gcc compiler it works OK. can anyone explain the problem of the compiler in the .c case?

  • 1
    "I tried to cast an `int(int, int)` function to an `int(int)` function" - **Why?** You should definitely not be doing that. It is undefined in both C and C++ to invoke a function through a pointer to incompatible type. –  Dec 18 '13 at 12:04

3 Answers3

2

GNU GCC recognises all of the following as C++ files, and will use C++ compilation regardless of whether you invoke it through gcc or g++: .C, .cc, .cpp, .CPP, .c++, .cp, or .cxx

From https://stackoverflow.com/a/1546107/1767861

In that case, gcc compiles it in c++, which seems to accept the cast. Why is that ? See https://stackoverflow.com/a/559671/1767861

Community
  • 1
  • 1
Thomas Ruiz
  • 3,611
  • 2
  • 20
  • 33
2

The problem is your signature for Myfunc1 and the function pointer you try to cast it to are of incompatible types. Instead, you need to do this:

ans = ((int(*)(int, int))(Myfunc1))(5, 5);

The link Thomas Ruiz posted explains why it is undefined behavior.


In summary:

Annex J.2

The behavior is undefined in the following circumstances:

-- A pointer is used to call a function whose type is not compatible with the pointed-to type (6.3.2.3).

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 pointed-to type, the behavior is undefined.

Community
  • 1
  • 1
1
#include <stdio.h>

int Myfunc1(int i, int z)
{
    return i;
}

int main()
{
    // define a function pointer and initialize it to NULL
    int (*ans)(int, int) = NULL;

    // get function pointer from function 'Myfunc1'
    ans = Myfunc1(5, 6);

    // call function using the pointer
    printf("ans: %d\n", (*ans));

    return 0;
}
karlphillip
  • 92,053
  • 36
  • 243
  • 426