How to Create Function in C: Syntax and Example
In C, you create a function by specifying its
return type, name, and parameters inside parentheses, followed by a block of code in curly braces. For example, int add(int a, int b) { return a + b; } defines a function named add that returns the sum of two integers.Syntax
A function in C has three main parts:
- Return type: The type of value the function gives back (like
int,void, etc.). - Function name: The name you use to call the function.
- Parameters: Inputs the function takes, listed inside parentheses, each with a type and name.
The function body is inside curly braces { } and contains the code to run.
c
return_type function_name(parameter_type parameter_name, ...) {
// code to execute
return value; // if return_type is not void
}Example
This example shows a function add that takes two integers and returns their sum. The main function calls add and prints the result.
c
#include <stdio.h> int add(int a, int b) { return a + b; } int main() { int result = add(5, 3); printf("Sum is %d\n", result); return 0; }
Output
Sum is 8
Common Pitfalls
Common mistakes when creating functions in C include:
- Forgetting to specify the return type, which causes errors.
- Not matching the return type with the actual returned value.
- Missing the
returnstatement when the function expects a return value. - Incorrect parameter types or missing parameters.
- Using the function before declaring or defining it (can be fixed by function prototypes).
c
#include <stdio.h> // Wrong: missing return type // int add(int a, int b) { // return a + b; // } // Correct: int add(int a, int b) { return a + b; } int main() { int result = add(2, 4); printf("Result: %d\n", result); return 0; }
Output
Result: 6
Quick Reference
Remember these tips when creating functions in C:
- Always specify the correct return type.
- Use meaningful function and parameter names.
- Declare functions before use or provide prototypes.
- Use
voidreturn type if no value is returned. - Keep function code focused on a single task.
Key Takeaways
Define a function with a return type, name, parameters, and a code block.
Use
return to send back a value if the return type is not void.Declare or define functions before calling them to avoid errors.
Match the return type with the actual returned value.
Use clear names and keep functions focused on one task.