C Functions Introduction
In this page:
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?
#include <stdio.h>
void greet() {
printf("Hello");
}
int main() {
greet();
greet();
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <stdio.h>
int square(int n) {
return n * n;
}
int main() {
printf("%d", square(4));
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <stdio.h>
int square(int n) {
return n * n;
}
int main() {
int result = square(5);
printf("%d", result);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#include <stdio.h>
void printMessage() {
printf("This function returns nothing");
}
int main() {
printMessage();
return 0;
}
Login to try C/C++/Java/PHP code in the editor
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
#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;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 8 topics to unlock
0/8 topics done
Complete these topics first: