Use of void in C prototypes

A giant died this morning. My condolences go to Dennis Ritchie’s family and friends.

In memory of Dennis, here is a short history lesson about C prototypes. Have you ever wondered why the following is legal?

#include <stdio.h>;

void foo () {
    printf("Goodbye, World!\n");

int main (int argc, char **argv) {
    foo(1); /* Call foo with a non-existent parameter */
    return 0;

$ gcc test.c -Wall -Werror
$ ./a.out
Goodbye, World!

This is legal for historical reasons. In pre-ANSI C function prototypes didn’t include parameters. C89 introduced parameters in prototypes, but it continued to recognize the old syntax for backwards compatibility.

If you want to declare a function foo that really takes no parameters, use void:

void foo (void);
  1. Anonymous says:

    This is actually quite useful for the occasional hard core optimization to save a clock cycle or 2 when calling a function. I used this instead of varargs, as it is more straightforward to implement. I usually will do something like this

    // header file
    void _function(); // don’t use this directly
    static inline funcX(int a) { _function(0, a); }
    static inline funcY(int a, int b) { _function(1, a, b); }

    // C file
    void _function(int mode, int arg1, int arg2)
    // in mode 0, arg2 is ignored
    // in mode 1, all args are used
    // body of function

    This way the caller only sets up the minimal arguments needed.