[英]dereferencing function pointer to function returning void throws error: void value not ignored as it ought to be
I am a beginner in C language.我是 C 语言的初学者。 Read various SO threads on function pointers.
读取 function 指针上的各种 SO 线程。 For instance, How does dereferencing of a function pointer happen , Function Pointer - Automatic Dereferencing [duplicate] , so I tried to do an experiment of mine.
例如, function 指针的解引用是如何发生的, Function 指针 - 自动解引用 [重复] ,所以我试着做一个我的实验。
Couldn't understand why this error is thrown since I am not using the void value anywhere..无法理解为什么会引发此错误,因为我没有在任何地方使用 void 值..
#include <stdio.h>
void f(int j) {
static int i;
if (j == 1)
printf("f: i entered this function main()\n");
else if(j == 2)
printf("f: i entered this function through pointer to function\n");
void (*recurse)(int);
recurse = *f; // "f" is a reference; implicitly convert to ptr.
if (i == 0){
i++;
*recurse(2);
} else
return;
}
int main(void)
{
f(1);
return 0;
}
GCC Version is 11.2.0 Compiler flags used include -std=c99 if I modify line 14 to recurse(2)
then the program runs smoothly. GCC 版本是 11.2.0 使用的编译器标志包括 -std=c99 如果我将第 14 行修改为
recurse(2)
,那么程序运行顺利。 No error or warning is thrown by the compiler.编译器不会抛出任何错误或警告。
$ gcc testing11.c @compilerflags11.2.0.txt -o testing11.exe
testing11.c: In function ‘f’:
testing11.c:14:10: error: void value not ignored as it ought to be
14 | *recurse(2);
| ^~~~~~~~~~
This expression statement这个表达式语句
*recurse(2);
is equivalent to相当于
*( recurse(2) );
So as the return type of the function is void
then you are trying to dereference the type void
.因此,由于 function 的返回类型是
void
,那么您正在尝试取消引用类型void
。
It seems you mean看来你的意思
( *recurse )(2);
Or you could just write或者你可以写
recurse(2);
because the expression *recurse
used in the first call will be again implicitly converted to a function pointer.因为第一次调用中使用的表达式
*recurse
将再次隐式转换为 function 指针。
So though this call for example所以虽然这个电话例如
( ******recurse )(2);
is correct nevertheless dereferencing the pointer expressions are redundant.是正确的,但是取消引用指针表达式是多余的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.