Functions in C – User Defined Functions, Arguments, Return Types

Functions in C – User Defined Functions, Arguments, Return Types | Tamil Technicians

Tamil Technicians – C Programming Course · Lesson 14

Functions in C – User Defined Functions, Arguments, Return Types

As your C programs grow larger, writing everything inside main() quickly becomes messy. You repeat the same logic many times, debugging becomes harder, and the code is difficult to read. The solution is to break your program into smaller, reusable pieces called functions.

In this lesson, we focus on user defined functions in C:

  • What functions are and why we use them.
  • How to define and call user defined functions.
  • Understanding arguments (parameters) and return types.
  • Difference between void functions and functions that return a value.
  • Best practices, mini-projects and a checklist for writing clean C functions.
C functions with main calling user defined functions using arrows – Tamil Technicians
Figure: A diagram of main() calling user defined functions with arrows, representing modular C programming.

What Is a Function in C?

A function in C is a self-contained block of code that performs a specific task. You can think of it as a small machine:

  • It can receive input values (called arguments or parameters).
  • It executes some logic.
  • It can optionally send back a result (called a return value).
Definition

A function is a reusable block of code with a name, a return type, an optional list of parameters, and a body (statements).

You already know one important function in every C program: int main(void) – the entry point of the program. In addition to main(), you can (and should) create your own functions to keep your code organized.

Why Use User Defined Functions?

Some key benefits:

  • Reusability – write once, call many times.
  • Modularity – split a big problem into smaller, manageable parts.
  • Readability – meaningful function names explain what the code does.
  • Testing – you can test each function separately.
  • Team work – different team members can work on different functions.

For example, instead of writing voltage calculation logic in many places, you can write a function: float calculateVoltage(float power, float current) and reuse it.

Syntax of a User Defined Function in C

General form:

return_type function_name(parameter_list) {
    // body: declarations + statements
}
  • return_type – data type of the value returned by the function (e.g., int, float, char, void).
  • function_name – identifier you use to call the function.
  • parameter_list – comma-separated list of parameters with types (can be empty).
  • body – code inside { } that is executed when the function is called.

Example – Function to Add Two Integers

#include <stdio.h>

int add(int a, int b) {
    int sum = a + b;
    return sum;     // return result to caller
}

int main() {
    int x = 10, y = 20;
    int result = add(x, y);   // function call

    printf("Sum = %d\\n", result);
    return 0;
}

Here, add is a user defined function that takes two int arguments and returns an int result.

Arguments & Parameters – What’s the Difference?

These two terms are often used interchangeably, but technically:

  • Parameters – variables in the function definition.
  • Arguments – actual values passed when calling the function.
int add(int a, int b) {   // a, b are parameters
    return a + b;
}

int main() {
    int x = 10, y = 20;
    int result = add(x, y);  // x, y are arguments
}
In C, function arguments are passed by value. That means the function receives a copy of the argument values. Changes inside the function do not affect the original variables in main(), unless you use pointers (pass-by-address), which we learn in pointer lessons.

Return Types in C Functions

The return type tells the compiler what type of value the function will send back to the caller.

Functions That Return a Value

int max(int a, int b) {
    if (a > b)
        return a;
    else
        return b;
}

Here, the function returns an int. Every return statement must return an int value.

void Functions (No Return Value)

void printLine(void) {
    printf("------------------------------\\n");
}

A void function does not return any value. You just call it for its side effects, like printing, logging, or updating global variables.

Check

If a function has a non-void return type (e.g., int, float), you must ensure that all possible control paths return a value of that type.

Examples of Different Function Types

1. No arguments, no return value

void greet(void) {
    printf("Welcome to Tamil Technicians!\\n");
}
greet();

2. Arguments, no return value

void printSum(int a, int b) {
    printf("Sum = %d\\n", a + b);
}
printSum(10, 20);

3. No arguments, returns a value

int readChoice(void) {
    int choice;
    printf("Enter choice: ");
    scanf("%d", &choice);
    return choice;
}

4. Arguments and return value

float average(float a, float b, float c) {
    return (a + b + c) / 3.0f;
}

Function Prototypes & Order of Definition

In C, the compiler must know the function’s signature (return type and parameter types) before it is called.

Two common patterns:

  1. Define functions before main().
  2. Use function prototypes before main() and define functions later.

Example with Function Prototype

#include <stdio.h>

/* Function prototype */
int add(int a, int b);

int main() {
    int result = add(5, 7);
    printf("Result = %d\\n", result);
    return 0;
}

/* Function definition */
int add(int a, int b) {
    return a + b;
}
Function prototypes are especially important when you split your code into multiple .c and .h files in larger projects.

Variable Scope and Functions

When you write functions, you must understand scope – where a variable is visible and valid.

Local Variables

Variables declared inside a function are local to that function. They are created when the function is called and destroyed when it returns.

void test() {
    int x = 10;    // local to test()
}

x cannot be used outside test().

Global Variables

Variables declared outside all functions are global. They can be accessed from any function in the same file (and other files with extern).

int counter = 0;  // global

void increment(void) {
    counter++;
}
For beginner projects, global variables can be convenient. But overusing globals makes code harder to maintain. Prefer passing values as function arguments whenever possible.

Technician-Style Examples with Functions

Example 1 – Voltage Calculation Function

Calculate voltage from power (in watts) and current (in amps): V = P / I.

#include <stdio.h>

float calculateVoltage(float power, float current) {
    if (current == 0.0f) {
        return 0.0f; // avoid divide by zero (simple handling)
    }
    return power / current;
}

int main() {
    float p, i;
    printf("Enter power (W): ");
    scanf("%f", &p);
    printf("Enter current (A): ");
    scanf("%f", &i);

    float v = calculateVoltage(p, i);
    printf("Voltage = %.2f V\\n", v);
    return 0;
}

Example 2 – Function to Find Maximum in an Array

#include <stdio.h>

int maxInArray(int a[], int n) {
    int i, max = a[0];
    for (i = 1; i < n; i++) {
        if (a[i] > max) {
            max = a[i];
        }
    }
    return max;
}

int main() {
    int arr[] = {12, 45, 7, 89, 23};
    int n = 5;
    int max = maxInArray(arr, n);
    printf("Max value = %d\\n", max);
    return 0;
}
Here, the array arr is passed as an argument to the function maxInArray(). Inside the function, it is treated as a pointer to the first element.

Mini-Projects Using Functions

  1. Simple Calculator: Write separate functions for add, subtract, multiply, and divide. Call them based on user menu choice.
  2. Student Result Module: Create a function to read marks, another to compute total and average, and another to determine grade based on average.
  3. Temperature Conversion: Write functions celsiusToFahrenheit() and fahrenheitToCelsius(). Use them in a menu-driven program.
  4. Billing System: Use functions to calculate item total, apply discount, and print final bill.
  5. Number Utilities: Write functions like isPrime(), isEven(), reverseNumber(), and reuse them in different programs.

Function Design Checklist

  • Did you give the function a clear, meaningful name?
  • Is there exactly one main job for this function (single responsibility)?
  • Is the return type correct and used properly?
  • Are parameter types and order clear and well-documented?
  • Does every non-void function return a value on all paths?
  • Can any repeated code be moved into a separate function?

Quick Summary – Functions, Arguments, Return Types

Concept Key Points
User defined function Block of code with name, parameters, and return type; called from other parts of the program.
Syntax return_type name(parameter_list) { body }.
Arguments / Parameters Values passed into the function; C uses pass-by-value by default.
Return type Type of result returned; use void when no result is needed.
Function prototype Declaration that tells the compiler about the function before use.
Scope Local variables exist only inside function; global variables exist for entire file.

Suggested Featured Image Prompt

Use this prompt in your AI image generator for the blog thumbnail:

“Flat modern 16:9 illustration on a light background. In the center, a simple flow diagram shows a `main()` function box at the top calling three smaller function boxes labeled `add()`, `average()`, and `printResult()`, with arrows going from `main()` to each function and back. On the left, a laptop screen displays C code with a function definition like `int add(int a, int b) { return a + b; }` and a call `sum = add(x, y);` highlighted. On the right, a South Indian / Tamil technician character is explaining the diagram with a pointer, next to small labels ‘Arguments’, ‘Return Value’, and ‘void function’. At the top, bold title text: ‘Functions in C’ and smaller subtitle: ‘User Defined Functions, Arguments, Return Types | Tamil Technicians’. Clean vector style, minimal colors, educational and high quality.”

FAQ: Functions in C

1. Can a C function return more than one value?

Not directly. A function can return only one value using the return statement. To effectively return multiple values, you can: use pointers (pass-by-address), return a struct, or modify global variables.

2. What happens if I forget to return a value from a non-void function?

This leads to undefined behaviour. The compiler may warn you, but if the code compiles, the returned value is unpredictable. Always make sure every control path in a non-void function has a proper return statement.

3. Are function parameters in C passed by reference or by value?

In C, all parameters are passed by value. The function receives copies of the argument values. To modify a variable in the caller, you must pass its address (pointer) and dereference it inside the function (this is often called pass-by-address).

4. Can I define a function inside another function in C?

Standard C does not allow nested function definitions. All functions must be defined at the top level (outside any other function). Some compilers offer nested functions as an extension, but it is not portable and not recommended for beginner code.

Category: C Programming Course · Lesson 14 – Functions in C

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top