CodeBlanks Logo Icon CodeBlanks

Defining functions

Learn how to define and call a function.

What is a function?

A function is a named, reusable block of code. The void return type means the function returns no value.

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

int main(void) {
    greet();
    return 0;
}

Defining a function does not run it; it only runs when called (greet();). This keeps code organized and free of repetition.

Calling a function

You call a function by its name with parentheses: greet();. The parentheses signal a function call.

void write(void) {
    printf("Line 1\n");
    printf("Line 2\n");
}

int main(void) {
    write();  /* prints two lines */
    write();  /* prints again */
    return 0;
}

You can call the same function multiple times; this avoids code duplication. main is also a function, and it is the first one called when the program starts.

Practice Define and call the greet function

Define void greet(void) with the body printf("Hello!\n");. Call greet() from main. Output should be Hello!.

Starter code

main.c
#include <stdio.h>

/* define greet function */

int main(void) {
    /* call greet */
    return 0;
}

Sample solution

main.c
#include <stdio.h>

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

int main(void) {
    greet();
    return 0;
}

Expected output

Hello!

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which of the following is a function definition?

  • greet();
  • void greet(void) { ... } Correct answer
  • int x = 5;
  • return 0;

Explanation: Return type, name and parentheses form a function definition.

2 Function body

Question
void greet(void) ____    printf("Hello\n");
}
Answer
void greet(void) {    printf("Hello\n");
}

Explanation: The body goes between curly braces.

3 Match function parts

Term Meaning
void return type
greet function name
(void) parameter
{ } body

All lessons in Beginner