C ยท Chapter 25 of 45

C Functions

A function is a reusable block of code that performs a specific task. Functions help organize code, avoid repetition, and make programs easier to test and maintain.

Every C function has a return type, a name, a parameter list, and a body. main() itself is just a special function that the operating system calls to start your program.

Syntax
returnType functionName(parameters) {
  // code
  return value;
}

Defining a function

A function definition specifies its return type, name, parameters in parentheses, and a body in braces. Use `return` to send a value back to the caller.

Calling a function

You call a function by writing its name followed by parentheses containing any arguments, like `add(2, 3)`. The function's return value can be stored, printed, or used in expressions.

Example 1 (c)
#include <stdio.h>

int add(int a, int b) {
  return a + b;
}

int main() {
  printf("%d\n", add(2, 3));
  return 0;
}
Output
5

add() takes two ints, returns their sum, and main() prints the result.

Example 2 (c)
#include <stdio.h>

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

int main() {
  greet();
  return 0;
}
Output
Hello!

A void function performs an action but returns nothing.

Key points

  • Functions have a return type, name, parameters and a body.
  • void functions perform an action but return no value.
  • Functions help avoid duplicated code and improve organization.
  • main() is the special entry-point function of every program.
๐Ÿ’ก Note: Breaking a large program into small, focused functions makes it much easier to test and debug.

๐Ÿ“ Quick Quiz

1. What keyword is used to send a value back from a function?

2. What return type is used when a function returns nothing?

3. Which function is automatically called when a C program starts?