0
0
CConceptBeginner · 3 min read

What is void in C: Meaning, Usage, and Examples

void in C is a keyword that means "no type" or "nothing." It is used to specify that a function does not return a value or that a pointer points to an unknown type.
⚙️

How It Works

Think of void as a label that says "empty" or "no data." When you see void before a function name, it means the function does not give back any value after it runs. It's like a machine that does a job but doesn't hand you anything when it's done.

Also, void can be used with pointers to mean "a pointer to something, but we don't know what." This is useful when you want a general pointer that can point to any type of data, like a universal remote control that can work with many devices.

💻

Example

This example shows a function that uses void to indicate it returns nothing, and a void pointer pointing to different data types.

c
#include <stdio.h>

void greet(void) {
    printf("Hello, world!\n");
}

int main() {
    greet();

    int num = 10;
    char letter = 'A';

    void *ptr;  // void pointer

    ptr = &num;  // points to int
    printf("Value pointed by ptr as int: %d\n", *(int *)ptr);

    ptr = &letter;  // points to char
    printf("Value pointed by ptr as char: %c\n", *(char *)ptr);

    return 0;
}
Output
Hello, world! Value pointed by ptr as int: 10 Value pointed by ptr as char: A
🎯

When to Use

Use void when you want to create a function that performs an action but does not return any value, such as printing a message or modifying data through pointers.

Use void pointers when you need a flexible pointer that can point to any data type, especially in functions that handle different kinds of data without knowing their exact types in advance.

For example, void pointers are common in generic data structures like linked lists or when writing functions that work with raw memory.

Key Points

  • void means "no type" or "nothing" in C.
  • Functions declared with void return no value.
  • void pointers can point to any data type but need casting to access data.
  • Using void helps write flexible and clear code.

Key Takeaways

void indicates no data or no return value in C.
Functions with void return type do not return anything.
void pointers are generic pointers that can point to any type.
You must cast void pointers before dereferencing them.
void helps make code flexible and clear about intent.