achoora achoora - 3 months ago 15
C Question

How to assign base address for a function pointer returning enum?

I have a function pointer which returns an enum

My enum is

typedef enum {
FIRST,
SECOND,
THIRD
} STATUS;


In the code some one has tried to assign a base address as

STATUS (*start_port)(void *,void *)= 0x80000001;


But it is throwing the warnings


"initialization makes pointer from integer without a cast"


and also


"ISO C90 forbids mixed declarations and code [-Wdeclaration-after-statement]"


I put the declaration separate

STATUS (*start_port)(void *,void *);


Then tried to assign the address to the function pointer in the following way

start_port = (unsigned int *)0x80000001;


it corrected the mixed declaration warning but a new error came up


"assignment from incompatible pointer type"


I would like to know how to properly type caste a function pointer to a fixed (constant) base address when the return value is an enum.

Answer
  1. You are declaring start_port of type function pointer and then try to assign a unsigned int * pointer to it, try

    STATUS (*start_port)(void *,void *) = (STATUS (*)(void *,void *)) 0x80000001;
    

    but this is terrible style and you should not do it.

  2. It's a warning telling you not to declare variables inside the code, it's something that is no longer a problem with modern versions of the standard but IMHO is still a good practice. Delcaring variables within the code makes it harder to follow the algorithm and the logic. Whereas declaring them only at the beginning of a block makes it easier to read the code as a whole. You know where the declarations are and you don't need to skip over parts of the code that are just "declarations".

  3. The same problem as (1), so the right way to cast is

    start_port = (STATUS (*)(void *,void *)) 0x80000001;