0

I have the following code:

#include <stdio.h>

typedef void (*myfunc_t)(int x);

myfunc_t myfunc(int x)
{
    printf("x = %d\n", x);

    return;
}

int main(void)
{
    myfunc_t pfunc = myfunc;

    (pfunc)(1);

    return 0;
}

When compiling for C99, standard C, I get an error:

prog.c: In function ‘myfunc’:
prog.c:9:6: error: ‘return’ with no value, in function returning non-void [-Werror]
      return;
      ^~~~~~
prog.c:5:14: note: declared here
     myfunc_t myfunc(int x)
              ^~~~~~
prog.c: In function ‘main’:
prog.c:14:26: error: initialization of ‘myfunc_t’ {aka ‘void (*)(int)’} from incompatible pointer type ‘void (* (*)(int))(int)’ [-Werror=incompatible-pointer-types]
         myfunc_t pfunc = myfunc;
                          ^~~~~~

A few questions in SO already explain that the return type of myfunc_t is void (e.g., here). So, why do I get these errors?

Note that if I change the type of myfunc from myfunc_t to void, then the program builds OK.

ysap
  • 7,723
  • 7
  • 59
  • 122
  • 1
    I don't understand what *you* don't understand. You function claims it returns a `myfunc_t`, but doesn't, It is then used in a context that expects a function returning `void`, which yours doesn't by declaration (forget about practice, which we already discussed). Changing to `void` fulfills *both* problems. – WhozCraig Nov 20 '19 at 05:01
  • `myfunc_t` is an alias for a prototype, isn't it? A type of a function, that is, that returns a `void`. I am using this prototype to define a function that returns a `void`. I am surely missing something here, but I still expect this to work. – ysap Nov 20 '19 at 05:07
  • 1
    It's a pointer-to-function *type* alias. Prototype has nothing to do with it. – WhozCraig Nov 20 '19 at 05:08
  • Yes, see my comment to https://stackoverflow.com/a/58947063/274579 Thanks. – ysap Nov 20 '19 at 05:11
  • You cannot use typedef to *define* a function, but you can use a typedef of a function type to *declare one*. If you've got a function *pointer* type like in the question then that can be used to *neither* declare *nor* define a function... – Antti Haapala -- Слава Україні Nov 20 '19 at 06:39

1 Answers1

2
myfunc_t myfunc(int x)

This statement creates a function myfunc which returns a function pointer myfunc_t

But in the function definition you are not returning anything. Also what this does is make myfunc incompatible with the myfunc_t type (return values are different)

What you need is to declare and define the function as

void myfunc(int x) 
{
     ...
}
Rishikesh Raje
  • 8,556
  • 2
  • 16
  • 31
  • I think I got my conceptual error. Contrary to what I wrote in the comment to the question, this is not rally a prototype. The definition of the function `myfunc` should have returned an object similar to `pfunc` in order to be correct. – ysap Nov 20 '19 at 05:10