开发者

C - What does this line mean?

开发者 https://www.devze.com 2022-12-16 11:52 出处:网络
I am trying to understand what the following line of the worst-ever-seen C code (from uboot project) mean:

I am trying to understand what the following line of the worst-ever-seen C code (from uboot project) mean:

rc = ((ulong (*)(bd_t *, int, char *[]))addr) (bd, --argc, &argv[1]);

What is it? A function call? Can it be more readable?

Thanks in advance for yo开发者_如何学运维ur help!


Yes, it's a function call.

It casts the value in addr to a function pointer which accepts (bd_t *, int, char *[]) as arguments and returns a ulong, and calls the function. It could be sugared into:

typedef ulong (*bd_function)(bd_t *bd, int argc, char *argv[]);

bd_function bdfunc = (bd_function) addr;

rc = bdfunc(bd, --argc, &argv[1]);

This might be overkill, to introduce a typedef if this only happens once, but I feel it helps a lot to be able to look at the function pointer's type separately.


It casts addr to a function pointer which accepts (bd_t *, int, char *[]) as arguments and returns a long, then invokes it with the arguments (bd, --argc, &argv[1]).


Not a direct answer to your question, but might be of interest:

  • Reading C Declarations

  • How To Read C Declarations

Start at the variable name (or innermost construct if no identifier is present. Look right without jumping over a right parenthesis; say what you see. Look left again without jumping over a parenthesis; say what you see. Jump out a level of parentheses if any. Look right; say what you see. Look left; say what you see. Continue in this manner until you say the variable type or return type.


ulong (*)(bd_t *, int, char *[]) is the type of a function that takes a pointer to a bd_t, an int, and a pointer to a char array, and returns a ulong.

The code is casting addr to such a function, and then calling it with bd, --argc, and &argv[1] as parameters, and assigning the result to rc.


addr must be the location in memory to a function that looks like

ulong *funcname(bd_t*, int, char*[])

and it's being called with the paramerers like

rc = funcname(bd, --argc, &argv[1]);


You're typecasting "addr" to a pointer to a function returning a ulong that takes a bd_t *, an int and a char *[] as parameters, and then calling the function with the parameters bd, --argc, &argv [1].

0

精彩评论

暂无评论...
验证码 换一张
取 消