← Back to C Course | Chapter 5: Functions | Lesson 1 of 8

C Functions Introduction

What is a Function?

A function bundles a specific task into a reusable, named block of code, so you can call that same logic from multiple places in your program instead of retyping it, and fix a bug in one place instead of many.

Example: What is a Function?

c
#include <stdio.h>
void greet() {
	printf("Hello");
}
int main() {
	greet();
	greet();
	return 0;
}

Defining a Function

Defining a function means writing its return type, a unique name, and a body in curly braces containing the statements it runs -- the compiler uses this definition to know exactly what the function does and expects.

Example: Defining a Function

c
#include <stdio.h>
int square(int n) {
	return n * n;
}
int main() {
	printf("%d", square(4));
	return 0;
}

Calling a Function

Calling a function -- writing its name followed by parentheses -- transfers control to that function's body; once it finishes, execution resumes right where the call was made, optionally with a value handed back.

Example: Calling a Function

c
#include <stdio.h>
int square(int n) {
	return n * n;
}
int main() {
	int result = square(5);
	printf("%d", result);
	return 0;
}

Void Functions

A void function performs an action (like printing something or updating a variable) without handing any value back to whoever called it -- the void keyword as the return type explicitly signals "nothing comes back."

Example: Void Functions

c
#include <stdio.h>
void printMessage() {
	printf("This function returns nothing");
}
int main() {
	printMessage();
	return 0;
}

Multiple Helper Functions

Splitting a program into several small helper functions, each responsible for one clear task, makes each piece easy to test and debug independently, rather than hunting for a bug inside one enormous block of code.

Example: Multiple Helper Functions

c
#include <stdio.h>
int square(int n) {
	return n * n;
}
int cube(int n) {
	return n * n * n;
}
int main() {
	printf("%d %d", square(3), cube(3));
	return 0;
}
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.