2.6 void类型
类型void代表变量中没有值。因此,你不能使用此类型来声明变量或常量。在以下场景,可以使用void类型。
2.6.1 函数声明中的void
没有返回值的函数具有void类型,例如,标准函数perror()以如下形式声明:
void perror ( const char * );
函数参数列表中的void表示此函数没有参数:
FILE *tmpfile( void );
因此,当你试图做类似tmpfile(“name.tmp”)的函数调用时,编译器将报错。如果函数声明时参数列表中没有使用void,C编译器将不知道关于函数参数的任何信息,因此,可能判断不出函数调用是否正确。
2.6.2 void表达式
Void表达式即没有值的表达式,例如,没有返回值的函数调用语句就是一种:
转换操作符(void)expression明确地丢弃了表达式的值,例如一个函数的返回值:
(void)printf("I don't need this function's return value!/n");
2.6.3 void指针
一个void类型的指针表示一个对象的地址,但它没有类型。你可以使用此无类型的指针来声明函数,因为它可以操作各种类型的指针参数,或返回一个”多用途”的指针,标准的内存管理函数是一个简单的例子:
void *malloc( size_t size );
void *realloc( void *ptr, size_t size );
void free( void *ptr );
如Example 2-3所示,你可以将一个void指针值赋给别一个对象的指针,反之亦然。不带有明确的类型转换。
Example 2-3. Using the type void
enum { ARR_LEN = 100 };
int main( )
{
int i, // Obtain some storage space.
*pNumbers = malloc(ARR_LEN * sizeof(int));
if ( pNumbers == NULL )
{
fprintf(stderr, "Insufficient memory./n");
exit(1);
}
srand( (unsigned)time(NULL) ); // Initialize the
// random number generator.
for ( i=0; i < ARR_LEN; ++i )
pNumbers[i] = rand( ) % 10000; // Store some random numbers.
printf("/n%d random numbers between 0 and 9999:/n", ARR_LEN );
for ( i=0; i < ARR_LEN; ++i ) // Output loop:
{
printf("%6d", pNumbers[i]); // Print one number per loop iteration
if ( i % 10 == 9 ) putchar('/n'); // and a newline after every 10 numbers.
}
free( pNumbers ); // Release the storage space.
return 0;
}