typo in function pointer variable declaration, but code compiles

情到浓时终转凉″ 提交于 2019-12-12 12:12:49

问题


While answering a question about function pointers, OP did that to declare a function pointer which takes 1 integer argument and returns nothing:

void *(intr_handlerptr)(int);  // wrong but compiles!!
intr_handlerptr = intr_handler;  // compiler error: cannot assign to this weird thing (lvalue required as left operand of assignment)

when the proper declaration is

void (*intr_handlerptr)(int);  // correct

What's funny is that the error occurs when assigning to this function pointer, not when declaring it (tested with gcc 7.3.1)

So what does that first line do?


回答1:


The expression void *(intr_handlerptr)(int); reads as "intr_handlerptr is a function taking an int and and returning a pointer to an unnamed thing (a void pointer). So the parenthesis around the function name have no use and are discarded. This is a prototype.

The expression void (*intr_handlerptr)(int); reads as "intr_handlerptr is a pointer to a function taking an int and returning nothing. The parenthesis are necessary to associate the name with the pointer type. This is a variable.

When assigning to the first, the compiler complains that you try to assign to "nothing" because the left-hand symbol is not a variable. Actually, the compiler only knows a prototype of that name in its symbol table. Of course, the second assignment statement is correct because you are assigning to a variable.



来源:https://stackoverflow.com/questions/53349871/typo-in-function-pointer-variable-declaration-but-code-compiles

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!