Home > Article > Backend Development > The function of void keyword in C language
void in C is a special keyword used to represent an empty type, which means data without a specific type. In C language, void is usually used in the following three aspects.
void helloWorld() { printf("Hello, World! "); }
In the above code, the return type of the helloWorld() function is void. It simply prints out the string "Hello, World!" without returning any value.
void printMessage(void) { printf("This is a message. "); }
In the above code, the printMessage() function does not receive any parameters, it simply prints out the string "This is a message."
void* ptr; int num = 10; float f = 3.14; char c = 'A'; ptr = # // void指针指向int类型的变量 ptr = &f; // void指针指向float类型的变量 ptr = &c; // void指针指向char类型的变量
In the above code, we declare a void type pointer ptr and let it point to the int type variable num, the float type variable f and the char type variable c.
It should be noted that since the void pointer cannot directly access and operate the data pointed to, when it is actually used, it usually needs to be converted to a specific type before operation can be performed. For example:
int* intPtr = (int*)ptr; // 将void指针转换为int指针 *intPtr = 20; // 通过int指针修改所指向的int类型的变量 printf("%d ", *intPtr); // 输出20
In the above code, we convert the void pointer ptr into the int pointer intPtr, and modify the pointed int type variable through the int pointer.
To sum up, void in C is a keyword used to represent empty types. It is widely used in function return types, function parameter types and pointer types.
The above is the detailed content of The function of void keyword in C language. For more information, please follow other related articles on the PHP Chinese website!