Programming in C — Functions
Hey. its the third tutorial article on Programming in C, We have covered the Fundamentals, Arrays & Strings in the previous posts.
Topics covered: Functions, Types of Functions, Parameter Passing, Recursion, Macros, Command Line Arguments
Functions in C
A function is a block of code that performs a specific task.
Example: When we want to build a house and paint it, we can divide the task into smaller parts:
One function to build the house & Another function to paint the house
Breaking a big task into smaller parts makes our program easy to write, understand, and change later.
A function is like a mini-program that does one specific job.
- You can send information to a function (these are called parameters).
- You can use the same function many times without rewriting the code.
Types of function
There are two types of function in C programming:
Standard library functions
- These are predefined functions/built-in functions that come with the C programming language, and the most familiar one —
main()which is used to execute code. - They are part of C standard libraries.
- You just need to include the right header file to use them.
You don’t write the code for these functions. They are already written, tested, and provided for your use.
User-defined functions
- These are functions that you create yourself to perform specific tasks.
- You write the definition, parameters, and logic.
- Useful when a task is repeated or code is too long.
#include <stdio.h>
void greet() {
printf("Welcome to C programming!\n");
}
int main() {
greet(); // calling user-defined function
return 0;
}You design the function based on what you need. It helps keep your code organized, reusable, and easy to understand.
Function Definition, Function Call, Function Prototype
Function definition contains the block of code to perform a specific task. In our example, adding two numbers and returning it.
// Syntax of function definition
returnType functionName(type1 argument1, type2 argument2, ...)
{
//body of the function
}When a function is called, the control of the program is transferred to the function definition. And, the compiler starts executing the codes inside the body of a function.
Get Divya Stephen’s stories in your inbox
Join Medium for free to get updates from this writer.
Control of the program is transferred to the user-defined function by calling it.
// Syntax of function call
functionName(argument1, argument2, ...);A function prototype is simply the declaration of a function that specifies function’s name, parameters and return type. It doesn’t contain function body. A function prototype gives information to the compiler that the function may later be used in the program.
// Syntax of function prototype
returnType functionName(type1 argument1, type2 argument2, ...);In Simple,
- Function Definition — Defines what a function does.
- Function Call — Calling the function to execute its code.
- Function Prototype — Declares the function before it’s used. Placed at the top or in a header file.
Parameter passing
Information can be passed to functions as a parameter. Parameters act as variables inside the function. Parameters are specified after the function name, inside the parentheses. You can add as many parameters as you want, just separate them with a comma:
// Syntax for parameter passing
returnType functionName(parameter1, parameter2, parameter3) {
// code to be executed
}NOTE: In programming, argument refers to the variable passed to the function. In the above example, two variables n1 and n2 are passed during the function call.
The parameters a and b accepts the passed arguments in the function definition. These arguments are called formal parameters of the function.
If n1 is of char type, a also should be of char type. If n2 is of float type, variable b also should be of float type, otherwise, the compiler will throw an error.
A function can also be called without passing an argument.
Example: How Function Works?
#include <stdio.h>
// Function declarations (prototypes)
void buildHouse(); // No parameters, no return
void paintHouse(char color[]); // Takes a string, no return
int calculateBudget(int materialCost, int laborCost); // Takes two integers, returns an integer
int main() {
// Function call to build the house
buildHouse();
// Function call to paint the house
paintHouse("Blue");
// Function call to calculate total budget
int total = calculateBudget(50000, 20000); // passing values to function
// Using the returned value
printf("Total budget for the house: ₹%d\n", total);
return 0;
}
// Function definition: Builds the house
void buildHouse() {
printf("Building the house...\n");
printf("Walls are up, roof is done, doors and windows added.\n");
}
// Function definition: Paints the house
void paintHouse(char color[]) {
printf("Painting the house with color: %s\n", color);
printf("Painting completed!\n");
}
// Function definition: Calculates and returns the total budget
int calculateBudget(int materialCost, int laborCost) {
int total = materialCost + laborCost;
return total; // return the result to main()
}
The return statement terminates the execution of a function and returns a value to the calling function. The program control is transferred to the calling function after the return statement.
Types of User-defined Functions in C Programming
- No Argument Passed and No Return Value
- No Arguments Passed But Returns a Value
- Argument Passed But No Return Value
- Argument Passed and Returns a Value
Recursion
Recursion is a programming technique where a function calls itself to solve a smaller instance of the same problem.
#include <stdio.h>
int factorial(int n) {
if (n == 0) return 1; // Base case
else return n * factorial(n - 1); // Recursive call
}
int main() {
int num = 5;
printf("Factorial of %d = %d", num, factorial(num));
return 0;
}Advantages and Disadvantages of Recursion
Passing Arrays to Functions
Arrays are passed by reference (actually, as pointers) to functions.
// Syntax
void display(int arr[], int size) {
for(int i = 0; i < size; i++)
printf("%d ", arr[i]);
}
//Example
#include <stdio.h>
int sumArray(int arr[], int size) {
int sum = 0;
for(int i = 0; i < size; i++) {
sum += arr[i];
}
return sum;
}
int main() {
int numbers[] = {2, 4, 6, 8, 10};
int size = sizeof(numbers) / sizeof(numbers[0]);
printf("Sum = %d", sumArray(numbers, size));
return 0;
}Macros — A macro is a preprocessor directive in C, used to define constants or functions that are replaced before compilation.
The C preprocessor is a macro preprocessor (allows you to define macros) that transforms your program before it is compiled. These transformations can be the inclusion of header files, macro expansions, etc.
All preprocessing directives begin with a # symbol. For example, #define PI 3.14
Why use Macros?
- To avoid repetitive code
- To improve readability
- To improve performance (no function call overhead)
Types of Macros
- Object-like Macros: Represent constants
- Function-like Macros: Represent expressions/functions
//Syntax
#define MACRO_NAME value_or_code
//Object-like Macro
#include <stdio.h>
#define PI 3.14159
int main() {
float r = 5;
float area = PI * r * r;
printf("Area = %.2f", area);
return 0;
}
//Function-like Macro
#include <stdio.h>
#define SQUARE(x) ((x) * (x))
int main() {
printf("Square of 4 = %d\n", SQUARE(4));
printf("Square of (2+3) = %d\n", SQUARE(2+3)); // will expand to ((2+3)*(2+3))
return 0;
}
Command Line Arguments
Command-line arguments are the values passed to main() function at runtime via the terminal/command line.
- They are used when we need to control our program from outside instead of hard-coding it.
- They make installation of programs easier.
// Syntax
//argc counts the number of arguments on the command line
//argv[ ] is a pointer array which holds pointers of type char which points to the arguments passed to the program.
int main(int argc, char *argv[])
// Example
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
if (argc != 3) {
printf("Usage: ./sum num1 num2\n");
return 1;
}
int a = atoi(argv[1]); // Convert string to int
int b = atoi(argv[2]);
printf("Sum = %d\n", a + b);
return 0;
}Compile & Run
Compile the above code using command: gcc name_of_file.c
gcc sum.c -o sum
./sum 10 20 //Outputs - 30It compiles sum.c and produces an executable file named sum in the current directory.
If you don’t use
-o, like this: gcc sum.cThen GCC creates an executable named
a.outby default.To run it: ./a.out 10 20









