开发者

When do we need & when passing a function?

I found these work types of code:

hash_init.key       = &hash_key_lc;  

And

ls->handler = init_connection;

Here both hash_key_lc and init_connection are functions,but one is with & the other not,why?

UPDATE

so they are the same thin开发者_运维问答g,but what's the rational??


This is identical to the following question: In C, what is the difference between `&function` and `function` when passed as arguments?

The accepted answer there:

There is no difference. For evidence see the C99 specification (section 6.7.5.3.8).

"A declaration of a parameter as ‘‘function returning type’’ shall be adjusted to ‘‘pointer to function returning type’’, as in 6.3.2.1."


reference/deference on a function is treated as a language special case in c,as function deserves this kind of special case ,it can't be passed by a certain value,you can only pass it by address/reference.


See C99 section 6.3.2.1, §4:

A function designator is an expression that has function type. Except when it is the operand of the sizeof operator or the unary & operator, a function designator with type ‘‘function returning type’’ is converted to an expression that has type ‘‘pointer to function returning type’’.

Thus, if foo is a function, the expressions foo and &foo are mostly interchangeable, in particular

foo == &foo

This is similar to how expressions with array type are implicitly converted to expressions with pointer type. Also, if fp is a function pointer, you can call it with or without dereferencing, ie the expressions

(*fp)(42)

and

fp(42)

are equivalent. Function calls are actually defined in terms of function pointers (section 6.5.2.2 §1) and not function designators, ie as far as language semantics go, *fp in the first example will implicitly converted back to fp before the parens are applied.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜