A function is a named block of C code that performs one task. Functions reduce repetition, divide a program into smaller modules, accept arguments when needed and can return a value to the caller.
return_type function_name(parameter_list) {
// statements
return value;
}
Use void when a function does not return a value. A function can also have no parameters, for example void show_message(void).
#include <stdio.h>
float average(float a, float b) {
return (a + b) / 2.0f;
}
int main(void) {
float result = average(10.0f, 11.0f);
printf("Average = %.2f\n", result);
return 0;
}
Output
Average = 10.50
Key point: the function receives two arguments and returns one float value.
If the function definition appears after main(), declare a prototype before it:
float average(float a, float b);
int main(void) {
float result = average(10.0f, 11.0f);
}
float average(float a, float b) {
return (a + b) / 2.0f;
}
The standard C library already provides toupper() in <ctype.h>. This user-defined version shows the character arithmetic directly. The older strupr() example is not part of ISO C.
#include <stdio.h>
char to_upper(char ch) {
if (ch >= 'a' && ch <= 'z') {
return (char)('A' + ch - 'a');
}
return ch;
}
int main(void) {
char ch = 'g';
printf("%c\n", to_upper(ch));
return 0;
}
Pass an address when the function needs to modify the caller's object.
#include <stdio.h>
void add_bonus(double *salary) {
*salary *= 1.15;
}
int main(void) {
double salary = 1000.0;
add_bonus(&salary);
printf("Final salary = %.2f\n", salary);
return 0;
}
When an array is passed to a function, also pass its element count instead of hard-coding the size.
#include <stdio.h>
#include <stddef.h>
int array_sum(const int values[], size_t count) {
int sum = 0;
for (size_t i = 0; i < count; i++) {
sum += values[i];
}
return sum;
}
int main(void) {
int values[] = {1, 2, 3, 4, 5};
size_t count = sizeof values / sizeof values[0];
printf("Sum = %d\n", array_sum(values, count));
return 0;
}
A normal local variable is created again for each call. A static local variable keeps its value between calls.
#include <stdio.h>
int running_sum(int value) {
static int sum = 0;
sum += value;
return sum;
}
int main(void) {
printf("%d\n", running_sum(5));
printf("%d\n", running_sum(3));
return 0;
}
Output
5
8
Practice basic C function questions →
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.