What is the void keyword in C?

The literal meaning of void is empty or blank. In C, void can be used as a data type that represents no data.

Usage

In C, void can be used as:

  • Return type of a function that returns nothing. Consider the code snippet below, which uses void as a return type.
#include<stdio.h>
void sum(int a, int b){
printf("This is a function that has no return type \n");
printf("The function prints the sum of its parameters: %d", a + b);
}
int main() {
sum(2, 5);
return 0;
}
  • Input parameter of a function that takes no parameters. Consider the code snippet below, which uses void as an input parameter.
#include<stdio.h>
int foo(void){
printf("This is a function that has no input parameters \n");
return 0;
}
int main() {
foo();
return 0;
}

Note: In C, foo() is different from foo(void). foo() means that the function takes an unspecified number of arguments. foo(void) is used for a function that takes no arguments.

  • Generic pointer declaration that has no type specified with it. Consider the code snippet below, which uses void as a pointer declaration.
#include<stdio.h>
int main() {
int a = 1;
char b = 'B';
float c = 3.3;
void * ptr = &a;
int *a2 = (int*) ptr;
printf("The number is: %d \n", *a2);
ptr = &b;
char *b2 = (char*) ptr;
printf("The character is: %c \n", *b2);
ptr = &c;
float *c2 = (float*) ptr;
printf("The float is: %f \n", *c2);
return 0;
}

Note: The void pointer cannot be dereferenced directly. It has to be type cast to a data type before being dereferenced.

Copyright ©2024 Educative, Inc. All rights reserved