Function without arguments

13 May 2020 — Written by Eiffel
#C#code

In C, it is possible to define a function without specifying its argument like void foo(). On a first sight, one would think that this function does not take any argument. In fact, it can take any argument and the following code highlights this behavior:

#include <stdlib.h>
#include <stdio.h>


void foo(){
	int val;

	asm volatile(
		/*
		 * By default, gcc uses AT&T assembler syntax where instructions run like
		 * that:
		 * instruction src, dst
		 * Also, register are prefixed with "%" and with inline asm we need to write
		 * "%%" to print a single "%".
		 * With the System V AMD64 ABI, rdi holds the first function argument.
		 */
		"mov %%edi, %0"
		: "=r" (val) // Output will be stored in val.
		: // There is not input.
		: // And the code does not modify any register.
	);

	printf("%d\n", val);
}

int main(void){
	foo(42);

	return EXIT_SUCCESS;
}

Compiling the above code does not produce errors since it is possible to give arguments to functions without defining their arguments. So, in this code, main calls foo with argument 42. Inside foo, I get this value by using inline assembly and reading register edi. Indeed, with System V AMD64 ABI (see Figure 3.4), this register contains the first function argument. The code effectively prints the value 42 on standard output.

Now, if we correct the function definition with void foo(void), it will not compile anymore with the following error:

error: too many arguments to function ‘foo’

To conclude, if you want to define a function which does not take any arguments, defines it with void as its argument.