Function Prototypes
Part of the Fundamentals section of Coddy's C journey — lesson 51 of 63.
In C, we can declare a function before we use it. A function prototype tells the compiler about a function's name, parameters, and return type before the actual function is defined.
Create a function prototype for a function that adds two integers:
int add(int a, int b);Then define the function:
int add(int a, int b) {
return a + b;
}The prototype is usually above the main, while the function itself is below the main, so the code looks cleaner.
Now you can use this function in the main:
int main() {
int result = add(5, 3);
printf("%d", result);
return 0;
}Without the prototype, if you call the function before its definition, you'll get a compiler error.
Challenge
EasyCreate a program that:
- Declares a function prototype for a function named
calculateAreathat takes two integers (length and width) and returns an integer. - Implements the function to calculate and return the area (length × width).
- In the main function, it gets two integers from the user, calls
calculateArea, and prints the result.
Cheat sheet
A function prototype declares a function before it's defined, telling the compiler about the function's name, parameters, and return type:
int add(int a, int b);Then define the function:
int add(int a, int b) {
return a + b;
}The prototype is usually placed above main, while the function definition goes below main:
int add(int a, int b); // prototype
int main() {
int result = add(5, 3);
printf("%d", result);
return 0;
}
int add(int a, int b) { // definition
return a + b;
}Without the prototype, calling a function before its definition will cause a compiler error.
Try it yourself
#include <stdio.h>
// Write your function prototype here
int main() {
// Declare and read variables
// Call your function and print the result here
return 0;
}
// Implement your function hereThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Control Flow
If StatementIf - ElseElse-IfSwitch CaseTernary Conditional OperatorRecap ChallengeNested If - Else7Functions
Declare a FunctionReturn TypesParametersRecap Challenge #1Recursion BasicsFunction PrototypesRecap Challenge #23Operators
Arithmetic OperatorsModulo OperatorIncrement/DecrementAssignment OperatorsRelational OperatorsLogical Operators Part 1Logical Operators Part 2Logical Operators Part 3Recap Challenge