我有一个想法,那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;
}
但是编译器提供了一个错误:
error: invalid use of void expression
int x = (int)x_function(520);
所以是我的想法错了吗? 是无效的功能简单的“功能不返回任何东西”?
是的,你的想法是错误的。一个void
函数不能返回任何东西。可以返回一个void *
的原因是因为,如@JohnBode评价提到“的语言标准指定的指针void
可转化为或者从任何对象的指针类型(6.3.2.3/1)”。该指针的值被压入堆栈,然后弹出当您返回。那么结果可以转换为任何类型的指针。随着void
函数,编译器不期望有什么流行从堆栈所以也没有。
是的,你是对的:void函数不返回任何东西,而指向void可以引用任何数据类型。
我认为这是一些回报,具有未知类型
这是不对的。
当一个函数的返回类型是void
,表示该功能不返回值。
用下面的功能的程序在C是无效:
void foo(int a)
{
return 0;
}
这里是我的编译器回馈编译时
t.c: In function ‘x_function’:
t.c:10:5: attention : ‘return’ with a value, in function returning void [enabled by default]
t.c: In function ‘main’:
t.c:15:5: attention : passing argument 1 of ‘x_function’ makes pointer from integer without a cast [enabled by default]
t.c:4:6: note: expected ‘void *’ but argument is of type ‘int’
t.c:15:5: erreur: utilisation invalide d'expression void
所以你不能返回的东西时,函数的返回类型是void
。
根据输入类型,我认为void *
是不准确的,你可以通过一个char **
类型并将其转换成任何你想要的类型。这就是在主函数args
完成收集在命令行你paramerters的把它给你的程序。
您是铸造是错误的。要投它的权利,这样做:
int x = ((int(*)(void*)x_function)(520);
如果你使用C语言编程的指针,你可以从void函数返回值。