函数指针变量声明中有错字,但代码可以编译 [英] typo in function pointer variable declaration, but code compiles
问题描述
回答有关函数指针的问题,OP这样做是为了声明一个函数指针,该函数指针带有1个整数参数且不返回任何内容:
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)
正确的声明是
void (*intr_handlerptr)(int); // correct
有趣的是,错误是在分配给该函数指针时发生的,而不是在声明它时发生的(使用gcc 7.3.1测试)
What's funny is that the error occurs when assigning to this function pointer, not when declaring it (tested with gcc 7.3.1)
那第一行是做什么的?
推荐答案
表达式void *(intr_handlerptr)(int);
读为"intr_handlerptr
是一个接受int并返回指向未命名对象的指针(空指针)的函数."函数名称周围的括号没有用,并且被丢弃了.这是一个原型.
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.
表达式void (*intr_handlerptr)(int);
读为"intr_handlerptr
是指向一个带int且不返回任何内容的函数的指针.必须使用括号将名称与指针类型相关联.这是一个变量.
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.
分配给第一个时,编译器会抱怨您试图分配给"nothing",因为左侧符号不是变量.实际上,编译器在其符号表中仅知道该名称的原型.当然,第二个赋值语句是正确的,因为要分配给变量.
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.
这篇关于函数指针变量声明中有错字,但代码可以编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!