What are User-Defined Functions in C- Learn C Programming Online Free

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

User-Defined Functions in C
Free embedded C course: Chapter 6, Lecture 3. Meet the three ingredients of user-defined functions in C: declaration, definition and call.

User-Defined Functions in C: Your Own Toolbox

Library routines cover common jobs, but no library knows how your motor controller should ramp its speed or how your sensor board should convert raw counts into degrees. For those jobs you write user-defined functions in C. This lecture of our free C programming course introduces the three ideas you need to create and use them, and it walks through two original programs that you can compile right now. If you want a free C tutorial that prepares you for professional embedded C programming, mastering this topic is non-negotiable.

What You Will Learn

  • The three parts of every user-defined function: declaration, definition and call
  • Why the compiler wants to see a prototype before a call
  • How to write functions that take no arguments and return nothing
  • How to write functions that take arguments and return a result
  • The difference between declaring and defining a function
  • How this pattern maps to header files in larger firmware projects

Prerequisites

Finish Lectures 1 and 2 of this chapter. You should be comfortable with int and double, printf, and simple arithmetic expressions.

The Three Things You Must Know

Creating and using a user-defined function always involves three separate ideas. They are easy to mix up at first, so let us give each a plain-language meaning.

IdeaPlain meaningWhere it appears
Declaration (prototype)Announces the name, parameter types and return typeTop of file or in a header
DefinitionContains the actual statements that do the workUsually after main, or in another file
CallAsks the function to run right nowInside main or another function
The three roles in one program
Declaration
tells the compiler it exists
Call
main uses the function
Definition
body does the real work

Example One: A Function with No Input and No Output

The simplest user-defined function does a fixed job. Here is a separator printer that draws a row of equals signs, handy for formatting serial log output.

#include <stdio.h>

void print_divider(void);          /* declaration */

int main(void)
{
    print_divider();               /* call */
    printf(" Boot complete\n");
    print_divider();               /* call again */
    return 0;
}

void print_divider(void)           /* definition */
{
    for (int i = 0; i < 24; i++) {
        putchar('=');
    }
    putchar('\n');
}
gcc -Wall -o ep_divider ep_divider.c
./ep_divider
========================
 Boot complete
========================

What Each Part Does

The first line announces print_divider. The keyword void before the name means it returns nothing, and void inside the parentheses means it accepts nothing. Inside main the function is called twice, which proves the reuse advantage from Lecture 1. The definition appears after main, which is legal because the declaration came first.

Example Two: Arguments In, Result Out

Most useful functions receive data and send a result back. This example converts a temperature in Celsius to Fahrenheit, a task that appears in countless sensor projects.

#include <stdio.h>

double to_fahrenheit(double celsius);     /* declaration */

int main(void)
{
    double room = 25.0;
    double f = to_fahrenheit(room);        /* call */

    printf("%.1f C is %.1f F\n", room, f);
    return 0;
}

double to_fahrenheit(double celsius)       /* definition */
{
    return celsius * 9.0 / 5.0 + 32.0;
}
25.0 C is 77.0 F

The call sits on the right side of an assignment, so the returned value flows into f. The parameter named celsius inside the function receives a copy of whatever value main passes, which here is the contents of room.

Why the Declaration Matters

The compiler reads your file from top to bottom. If it meets a call to a name it has never heard of, old compilers silently assumed the function returned int, a rule that caused many hidden bugs, and modern C standards no longer allow it. A prototype eliminates the guesswork: the compiler can check that you passed the right number and types of arguments and can apply correct conversions.

Warning: If you define a function above main, the definition itself serves as a declaration, and a separate prototype is optional. Many professional teams still write prototypes in headers so that other files can use the function.

Declaration Versus Definition

These two words are often confused. A declaration never allocates code; it only describes the interface. A definition provides the body. You may declare a function many times, but you may define it only once in the whole program.

Typical multi-file firmware layout
temperature.h
declares to_fahrenheit
temperature.c
defines to_fahrenheit
main.c
includes header, calls it

In this layout the header is the contract, the source file is the implementation, and any file that includes the header can call the function. This is the same relationship you saw between math.h and the math library in the previous lecture.

Real-World Uses in Firmware

  • led_set(int on) hides which GPIO pin drives the LED.
  • crc8(const unsigned char *data, int len) checks packet integrity wherever packets are received.
  • delay_ms(unsigned ms) lets application code wait without knowing timer details.
  • battery_percent(int millivolts) converts a raw measurement into a user-friendly number.

Step-by-Step Trace of the Temperature Program

Tracing a program by hand is the fastest way to understand user-defined functions in C. Follow the Celsius example from above in order. First the compiler reads the prototype and learns that to_fahrenheit accepts one double and returns a double. Execution then begins at main, where the variable room receives 25.0. Next the call is reached: the value 25.0 is copied into the parameter celsius, control jumps into the function body, the expression evaluates to 77.0, and the return statement delivers that number back. Finally the assignment stores 77.0 in f and printf prints both numbers.

Notice that the name celsius exists only inside the function. The variable room belongs to main. They happen to hold the same number during the call, but they are two separate storage locations.

Naming Conventions for Firmware Functions

Teams that write embedded C programming code for years settle on naming rules so that every engineer can guess a function’s name without searching. A common pattern is module_action, such as adc_start, adc_read and adc_stop. Typing the module prefix in an editor then lists every related function through autocomplete. Another useful habit is to pick verbs for actions and nouns or question words for queries, for example buffer_clear versus buffer_is_full.

Poor nameBetter nameWhy it is better
do_itmotor_startSays which module and which action
calcto_fahrenheitDescribes the exact conversion
checkbattery_is_lowReads naturally inside an if statement

Mini Exercise: Build a Tiny Converter Module

To practice, create three prototypes in a header: one converting Celsius to Fahrenheit, one converting Fahrenheit back to Celsius, and one that prints a temperature with its unit. Put the definitions in a separate source file and call all three from main. When the program works, deliberately change a parameter type in the definition but not in the prototype, compile with -Wall, and read the error message. Seeing the compiler complain teaches the value of prototypes better than any explanation can.

Common Mistakes with User-Defined Functions in C

  1. Prototype and definition disagree. A different parameter type between the two causes confusing errors.
  2. Forgetting the semicolon after a prototype. A declaration is a statement and needs one.
  3. Calling before declaring. The compiler cannot validate the call.
  4. Defining the same function in two files. The linker reports a multiple definition error.
  5. Empty parentheses confusion. In a declaration, () does not promise “no arguments” in older C, so write (void) when you mean none.

Best Practices, Performance and Security

Good habits

  • Write the prototype first; it forces you to think about the interface.
  • Use const on pointer parameters that the function only reads.
  • Keep helper functions private with static to avoid name clashes.
  • Validate arguments at the top of any function that handles external data.
  • Let the compiler inline tiny helpers; do not manually duplicate code for speed.

Summary and Key Takeaways

  • User-defined functions need a declaration, a definition and a call.
  • A prototype lets the compiler verify every call.
  • Functions can take no input, take input, return a value, or return nothing.
  • Declarations belong in headers; definitions belong in source files.
  • These patterns scale from small exercises to complete embedded C programming projects.

The next lecture dissects the function definition itself: header, body, return type, formal arguments and local variables.

Frequently Asked Questions

Do I always need a prototype?

Not if the function is defined before it is called, but prototypes are strongly recommended for clarity and multi-file projects.

Can main call a function defined later in the file?

Yes, as long as a prototype appears earlier.

Can I declare a function more than once?

Yes, repeated identical declarations are allowed. Only one definition may exist.

What does void mean in a parameter list?

It states clearly that the function takes no arguments.

Where should I put prototypes in a big project?

In a header file included by every source file that calls the function.

Can a function call another function?

Yes. Functions can call each other freely, as long as each callee is declared before use.

Is user-defined function knowledge required for embedded interviews?

Absolutely. It is one of the most frequently tested topics in embedded C programming interviews.

Master C Functions for Free

Continue this free C programming course and learn exactly how a function definition is built.

💬 Need help or career guidance? Ask us!Contact Us →

2 Comments

Leave a Reply

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

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →