psihodelia
psihodelia

Reputation: 30522

C - What does this line 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 your help!

Upvotes: 11

Views: 742

Answers (6)

Mitch Wheat
Mitch Wheat

Reputation: 300769

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

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.

Upvotes: 4

unwind
unwind

Reputation: 400109

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.

Upvotes: 35

John Boker
John Boker

Reputation: 83729

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]);

Upvotes: 2

Skizz
Skizz

Reputation: 71120

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].

Upvotes: 1

Graeme Perrow
Graeme Perrow

Reputation: 57278

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.

Upvotes: 2

Mike Weller
Mike Weller

Reputation: 45598

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]).

Upvotes: 12

Related Questions