简体   繁体   中英

typo in function pointer variable declaration, but code compiles

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM