function cast leads to gcc abort command

Jonathan Wakely jwakely.gcc@gmail.com
Wed Dec 18 12:37:00 GMT 2013


On 18 December 2013 12:25, buzush wrote:
> hi,
>
> in the following code 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.)

When the file has a .cpp extension the C++ compiler is used, which has
different diagnostics.

> can anyone explain the problem of the compiler in the .c case?

Your program has undefined behaviour in both cases, so any behaviour
is allowed, including (but not limited to) aborting or executing
without error.



More information about the Gcc-help mailing list