C Function Declaration
Introduction to Function Declarations
Function declarations (also called function prototypes) tell the compiler about a function's interface before it's defined. They specify the function's name, return type, and parameter types, allowing the compiler to check function calls for correctness before the actual function definition is encountered.
Declarations enable you to define functions in any order and help catch errors early by ensuring function calls match their expected signatures.
Function Declaration Syntax
return_type function_name(parameter_type1 name1, parameter_type2 name2, ...);
Declaration vs Definition
Aspect | Declaration (Prototype) | Definition |
---|---|---|
Purpose | Tells compiler about function interface | Provides actual implementation |
Syntax | Ends with semicolon | Has function body in {} |
Storage | No code emitted (interface only) | Emits code for the function body |
Multiplicity | May appear multiple times if identical/compatible | Exactly one definition per program (ODR) |
Why Use Function Declarations
- Enable calling functions before they're defined
- Allow functions to be defined in any order
- Provide compile-time type checking and correct default promotions
- Make code more readable and organized
- Essential for header files and multi-file programs
Practical Example
#include <stdio.h>
// Function declarations (prototypes)
int multiply(int a, int b);
void greetUser(const char *name);
double calculateCircleArea(double radius);
aint main(void) {
// Can call functions before their definitions
int result = multiply(5, 3);
printf("Multiplication result: %d\n", result);
greetUser("Alice");
double area = calculateCircleArea(2.5);
printf("Circle area: %.2f\n", area);
return 0;
}
// Function definitions
int multiply(int a, int b) {
return a * b;
}
void greetUser(const char *name) {
printf("Hello, %s!\n", name);
}
double calculateCircleArea(double radius) {
return 3.14159 * radius * radius;
}
Multiplication result: 15 Hello, Alice! Circle area: 19.63
Common Declaration Patterns
Different ways to declare functions based on their parameters:
// Function with no parameters
void doSomething(void);
// Function with unspecified parameters (avoid this in modern C)
void doSomething();
// Function with specific parameters
int processData(int count, const double values[]);
// Function with variable parameters (varargs)
#include <stdarg.h>
int sumNumbers(int count, ...);
Prototypes in Headers (Multi-File)
Place function declarations in header files so they can be shared across translation units.
example.h:
int add(int a, int b);
main.c:
#include "example.h"
int main(void) { return add(2, 3); }
example.c:
#include "example.h"
int add(int a, int b) { return a + b; }