Lesson 8.3. Void keyword


This keyword void is used when a function returns no value or accepts no parameters. Here is an example of a function with void:

int main (void) {
  return 0;

Function without returned value

When a function does not return a value, then the keyword void must be prefixed to its declaration. Here is an example of a function that displays an integer and returns nothing:

void println(int n) {
  printf ("%d\n", n);

In this type of function, the return keyword can be used, but it is only used to end the execution of the function.

Function without parameters

If a function accepts no arguments, you must specify void between the parentheses to inform the compiler (and the users) that it does not receive any parameters. For example, the standard function rand() returns a pseudo-random number:

int rand(void);

Note that some compilers accept the omission of the void keyword between the parentheses. However, it is preferable to write it systematically in order to ensure the portability of the code to another compiler.


Exercise 1

Write a function printBase(unsigned int n, unsigned char base) which displays the integer n in the base base followed by a line feed:

The base parameter can take only three values:

We provide the beginning of the main program that asks the user to enter an integer. Complete this program so that the integer entered is displayed in the three bases:

Enter a positive integer: 185
In octal: 271
In decimal: 185
In hexadecimal: b9

Exercise 2

Write a function input() that captures a value from the keyboard and returns the value. The body of the input() function should contain only 3 lines:

Test the function with the following main program:

int main(void) {

  float n1, n2;

  // Ask the values
  printf ("Enter a value: ");
  n1 = input();
  printf ("Enter another value: ");
  n2 = input();

  // Display the average
  printf ("Average = %.2f\n", (n1+n2)/2);

  return 0;
Enter a value: 12.4
Enter another value: 13.7
Average = 13.05


Which of these functions do not receive any parameters?

Check Bravo! A function without parameters contains void or nothing between the parentheses Try again...

Which of these functions do not return any parameters?

Check Bravo! void must precede the function name to indicate that it does not return a value. Try again...

Let's consider the following function, which statements are correct?

void update(void);
Check Bravo! It is quite common to write functions that receive and return no parameters, especially on embedded systems. Try again...

Which functions receive no input parameters and return 2?

Check Bravo! In C, a function can only return one value at most. Try again...

See also

Last update : 11/28/2022