Function prototypes - Time & Space Complexity
We want to see how the time a program takes changes when it uses function prototypes.
Does adding a function prototype affect how long the program runs?
Analyze the time complexity of the following code snippet.
#include <stdio.h>
// Function prototype
int add(int a, int b);
int main() {
int result = add(5, 3);
printf("Result: %d\n", result);
return 0;
}
int add(int a, int b) {
return a + b;
}
This code declares a function prototype for add, then calls it in main.
Look for loops or repeated calls that take time.
- Primary operation: One call to the
addfunction. - How many times: Exactly once in this example.
Since the function is called only once, the time does not grow with input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 call to add |
| 100 | 1 call to add |
| 1000 | 1 call to add |
Pattern observation: The number of operations stays the same no matter the input size.
Time Complexity: O(1)
This means the program runs in constant time because it calls the function only once.
[X] Wrong: "Adding a function prototype makes the program slower because it adds extra code."
[OK] Correct: The prototype only tells the compiler about the function; it does not add extra work when running the program.
Understanding how function prototypes affect program speed shows you know how code structure relates to performance.
"What if the function add was called inside a loop that runs n times? How would the time complexity change?"