我有一个想法,void 函数并不意味着“不返回任何内容”,而是返回一些未知类型的内容,例如void *您可以将它与任何类型的数据一起使用的指针。所以我写了以下代码来确定:
#include <stdlib.h>
#include<stdio.h>
void x_function(void *);
void x_function(void *d)
{
printf("the integer value of d is %d \n " , *(int *)d );
printf("the string value of d is %s \n " , (char *)d );
printf("the character value of d is %c \n " , *(char *)d );
printf("the double value of d is %lf \n " , *(double *)d );
return 10;
}
int main()
{
int x = (int)x_function(520);
printf("The Value is : %d" , x);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但是编译器报错:
error: invalid use of void expression
int x = (int)x_function(520);
Run Code Online (Sandbox Code Playgroud)
所以我的想法错了吗?
void 函数只是“不返回任何内容的函数”吗?
是的,你的想法是错误的。一个void函数不能返回任何东西。您可以返回 a 的原因void *是,正如@JohnBode 在评论中提到的那样,“语言标准指定可以将指向的指针void转换为任何对象指针类型(6.3.2.3/1)或从任何对象指针类型(6.3.2.3/1)”。指针的值被压入堆栈,然后在您返回时弹出。然后可以将结果转换为任何类型的指针。对于void函数,编译器不需要从堆栈中弹出任何东西,所以它不会。
| 归档时间: |
|
| 查看次数: |
20423 次 |
| 最近记录: |