Functions are the core concept of C programming,functions are independent code blocks that perform specific tasks, which can accept input parameters, execute operations, and return results.They allow for organizing code into reusable modules, improving code readability, maintainability, and reusability.Function DefinitionDefines the specific content that the function executes.
return_type function_name(parameter_list) { // function body return expression; // if return type is not void}
Function DeclarationDeclares the format of the function, letting users know how to call it.
return_type function_name(parameter_list);
Function declarations are optional, but function definitions are required.
#include <stdio.h>
/* Function declaration, generally can be placed in a header file you write yourself
Because the main function uses the max function, and the code is used before the definition of the max function
If not declared before main, it will cause a compilation error: error: call to undeclared function 'max'*/
int max(int a, int b);
// Function definition, because add is defined before its use in main
// so it does not need a declaration
int add(int a, int b) { return a + b;}
int main(int argc, char *argv[]) { int x = 10; int y = 20; int m = 0; int total = 0;
m = max(x, y); // function call total = add(x, y); // function call printf("Maximum: %d, Total: %d\n", m, total);
return 0;}
// Function definition
int max(int a, int b) { return (a > b) ? a : b;}
Output:
Maximum: 20, Total: 30
Variable Argument Functions
C language supports variable argument functions, such asprintf. You need to includestdarg.h header file.
#include <stdio.h>
#include <stdarg.h>
int sum(int count, ...) { int total = 0; va_list args;
va_start(args, count); for (int i = 0; i < count; i++) { total += va_arg(args, int); } va_end(args); return total;}
int main(int argc, char *argv[]) { printf("Total: %d\n", sum(3, 10, 20, 30)); printf("Total: %d\n", sum(5, 1, 2, 3, 4, 5)); return 0;}
Output:
Total: 60
Total: 15