typo in function pointer variable declaration, but

2019-06-19 02:13发布

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条回答
不美不萌又怎样
2楼-- · 2019-06-19 03:03

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.

查看更多
登录 后发表回答