I have the function
uint8_t Authorization_getRole (char const* userId, UsertoRole_T const *roleTable)
and in the main program I have:
given_Role = Authorization_getRole (userId, roleTable)
I want to replace the function call with a function pointer:
uint8_t (*getRole_ptr)()
given_Role = &getRole_ptr;
My questions are:
Where do I initalize the function pointer getRole_ptr?
How do I initialize the function pointer?
Is the syntax below correct?
getRole_ptr = Authorization_getRole (userId, roleTable)
I'd always recommend a typedef with function pointers. Then, you would write:
// Make sure to get the function's signature right here
typedef uint8_t (*GetRole_Ptr_T)(char const*, UsertoRole_T const*);
// Now initialize your pointer:
GetRole_Ptr_T getRole_ptr = Authorization_getRole;
// To invoke the function pointed to:
given_Role = getRole_ptr(userId, roleTable);
Regarding "Where do I initalize the function pointer getRole_ptr?": Depends on your requirements. You can do it when declaring the pointer, as I did in my example, or you can change the pointer later on by assigning to it:
getRole_ptr = Some_function_with_correct_signature;
uint8_t (*getRole_ptr)()
The function pointer needs to have exactly the same format as the pointed at function. So you need to specify the types of the two parameters:
uint8_t (*getRole_ptr)(const char*, const UsertoRole_T*);
(Otherwise C will take your code to a horrible place called implicit land, where bizarre creatures like "default argument promotions" exist. You don't even want to know what that is, just write out the full function with proper parameters.)
Hopefully you can tell that the function pointer declaration just written looks like unreadable crap. Therefore you should use a typedef instead:
typedef uint8_t (*role_ptr_t)(const char*, const UsertoRole_T*);
...
role_ptr_t getRole_ptr;
Where do I initalize the function pointer getRole_ptr? How do I initialize the function pointer?
Formal initialization can only occur on the line where you declare a variable. So if you for some strange reason must use initialization, rather than assignment, then you have to do so on the same line as the declaration:
role_ptr_t getRole_ptr = Authorization_getRole;
Is the syntax below correct?
No. See correct syntax above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With