FUNCTIONS IN C

Dev Frank
7 min readMar 5, 2024

--

In C programming, a function is a block of code that performs a specific task and can be called from other parts of the program. It serves as the fundamental component of a C program, promoting organization and the reuse of code. It is a shorthand for calling a bunch of statements.

The tasks assigned to a function are enclosed within curly braces { } and execute specific operations.
A function can be used to call or execute multiple statements at one time.

SYNTAX OF FUNCTION IN C

The syntax of functions in C consists of three main parts:

  1. Function Declaration
  2. Function Definition
  3. Function Call

Function Declaration

In declaring a function we have to provide its return type, and the number and type of its parameters.

Syntax

return_type function_name(parameter1_type parameter1, parameter2_type parameter2, ...);

return_type:

  • Specifies the data type of the value that the function will return.
  • It can be any valid data type in C, including int, float, double, char, or a user-defined type.

function_name:

  • Identifies the name of the function.

It should follow the rules for naming identifiers in C (e.g., start with a letter, can contain letters, digits, and underscores).

(parameter1_type parameter1, parameter2_type parameter2, …):

  • Inside the parentheses, you declare the parameters that the function expects.
  • Each parameter consists of a data type (parameter1_type, parameter2_type, etc.) followed by the parameter name (parameter1, parameter2, etc.).
  • If the function doesn’t require any parameters, you can leave the parentheses empty.

NOTE: A parameter in programming is a variable used in a function to receive input values from the calling code. Parameters allow functions to accept and process different data, enhancing flexibility and reusability. They act as placeholders for values that are provided when the function is called.

Example

int add(int a, int b);  // Example function declaration

Parameters in a function declaration are not compulsory. Whether a function has parameters or not depends on the specific requirements of the task the function is designed to perform.

If a function does not require any parameters, the parentheses can be left empty:

int exampleFunction();  // Function with no parameters

Function Definition

The actual code of the function is defined separately from its declaration. It provides the actual implementation of the tasks the function is designed to perform.

It includes the code enclosed within curly braces { } that specifies the operations, computations, or actions the function will execute when called. The definition completes the function's structure initiated by its declaration.

Syntax

return_type function_name(parameter1_type parameter1, parameter2_type parameter2, ...) {
// Function body (code)
// ...
// Return statement (if applicable)
}
  • return_name: Specifies the data type of the value that the function will return. It can be any valid data type in C.
  • function_name: Identifies the name of the function. It should follow the rules for naming identifiers in C.
  • (parameter1_type parameter1, parameter2_type parameter2, …): Inside the parentheses, you declare the parameters that the function expects. Each parameter consists of a data type followed by the parameter name.
  • { … }: The curly braces contain the actual code or body of the function. This is where you define the operations the function will perform.
  • Return statement (if applicable): If the function returns a value, you use the return statement followed by the value to be returned.

Here’s a simple example:

// Function definition
int addNumbers(int a, int b) {
int sum = a + b;
return sum; // Return statement
}

In this example:

  • int is the return type.
  • addNumbers is the function name.
  • (int a, int b) are the parameters.
  • { … } contains the function body with the code to add two numbers.
  • return sum; returns the calculated sum.

Function Call

A function call A function call is a statement that instruct the compiler to carry out the operations specified within the functions.

It involves using the function’s name along with parentheses and, if applicable, providing values (arguments) for its parameters. The program temporarily transfers control to the function, executes its code, and returns the result to the calling code.

Here’s the basic syntax of a function call in C:

return_type result = function_name(argument1, argument2, …);

return_type: The data type of the value that the function returns.

result: A variable that stores the value returned by the function.

function_name: The name of the function to be called.

(argument1, argument2, …): The values (arguments) passed to the function. The number and types of arguments must match the function’s declaration.

Example:

#include <stdio.h>
// Function declaration

int add(int a, int b);

int main() {
// Function call
int sum = add(3, 5);

// Output the result
printf("The sum is: %d\n", sum);
return 0;
}

// Function definition
int add(int a, int b) {
return a + b; // Returns the sum of a and b
}

Outputs

The sum is: 8

In this example, add(3, 5) is the function call. It transfers control to the add function, which calculates the sum of 3 and 5 and returns the result. The returned value is then stored in the variable sum and printed to the console.

Function Return Statement

The return statement in programming is used to send a value back from a function to the part of the program that called it. The return type in the function declaration specifies the type of value that should be returned.

It marks the end of the function’s execution and passes the specified result, allowing the calling code to retrieve and use that value for further operations. Functions with a return type of void do not return any value.

// Function definition with int return type and two parameters
int addNumbers(int a, int b) {
// Function body to add two numbers
int sum = a + b;

// Return statement
return sum;
}

In this example, int is the return type, addNumbers is the function name, (int a, int b) are the parameters, { … } contains the function body, and return sum; is the return statement.

Function Parameters

Function Arguments

Arguments are values or variables provided to a function during its call. They serve as input, supplying information the function requires to perform its task. Arguments correspond to the parameters defined in the function’s declaration, influencing its behavior and outcome.

Syntax

return_type result = function_name(argument1, argument2, ...);
  • return_type: The data type of the value that the function returns.
  • result: A variable that stores the value returned by the function.
  • function_name: The name of the function to be called.
  • (argument1, argument2, …): The values (arguments) passed to the function. The number and types of arguments must match the function's declaration.

Types Of Functions

Functions can be classified into different types based on their characteristics and purpose. There are basically two types of functions in C programming

  1. Standard Library Functions:

This is also known as “Built-in Functions”. These functions are provided by the C standard library and can be used directly in C programs. Library functions are built into the C language and perform essential operations.

Built-in functions can be used directly without declaration or definition, one of its advantage. On the other hand, user-defined functions require declaration and definition before utilization, introducing an additional step in the programming process.

Examples of some Built-in Functions

printf(), scanf(), sqrt(), pow(), strlen(), strcpy(), malloc(), free() .etc.

Example

#include <stdio.h>
#include <math.h>

int main() {
double base = 2.0;
double exponent = 3.0;

// Calculating 2^3 using pow()
double result = pow(base, exponent);

printf("Result: %.2lf\n", result);

return 0;
}

In this example, pow(2.0, 3.0) calculates 2 raised to the power of 3, resulting in 8.0. The result is then printed to the console. The pow() function returns a double value.

Output

Result: 8.0

BENEFIT OF STANDARD LIBRARY FUNCTIONS

  • These functions are designed to work efficiently, making your programs run faster.
  • Saves time by using tested and proven solutions from the standard library instead of building everything from scratch.
  • Reuse well-tested functions in different projects without having to rewrite the same code.
  • Ensure consistency in your code and lower the risk of mistakes by using standardized functions.
  • Code using standard library functions can easily adapt to different systems and platforms.

2. User Defined Functions:

User-Defined Functions (UDFs) in C programming are functions created by the programmer to perform specific tasks tailored to their program’s requirements.

When we create a specific function for a particular situation and it’s not something already provided (not defined in any header file), we have to make our own rules for how that function works. We do this by declaring (saying we’ll use) and defining (giving the details of) the function in our code.

BENEFIT OF USER DEFINED FUNCTIONS

1. Breaking Down Programs:
Instead of dealing with one big, complicated program, User-Defined Functions help us split it into smaller, easier-to-understand parts.

2. Testing Made Simple:
Each part (function) can be tested on its own, making sure it does its job correctly. This helps ensure that the whole program works reliably.

3. Easy Problem-Solving:
If something goes wrong, we can focus on specific functions to find and fix issues. This makes problem-solving much simpler.

4. Efficient Updates:
When we need to change or add something, we can do it in just one part (function), making updates quicker and more straightforward.

5. Clearer Logic:
User-Defined Functions make the code easier to read by putting specific tasks into well-named sections. This makes the overall plan of the program clearer.

6. Reuse to Reduce Waste:
Once we create a function, we can use it again in different parts of the program or even in other projects. This reduces unnecessary repetition of work.

Example:

#include <stdio.h>

// Function declaration
int calculateSquare(int number);

int main() {
// Get user input
int input;
printf("Enter a number: ");
scanf("%d", &input);

// Function call
int result = calculateSquare(input);

// Output the result
printf("The square of %d is: %d\n", input, result);

return 0;
}

// Function definition
int calculateSquare(int number) {
// Calculate and return the square
return number * number;
}

Output

For instance, if the user enters 5, the output would be

Enter a number: 5
The square of 5 is: 25

In this program:

  • int calculateSquare(int number); is the function declaration, specifying that calculateSquare takes an integer parameter and returns an integer.
  • int result = calculateSquare(input); is the function call, where the user input is passed to the calculateSquare function, and the result is stored in the variable result .
  • The function definition int calculateSquare(int number) includes the logic to calculate the square of the provided number.

--

--

Dev Frank

Passionate tech enthusiast, diving deep into the world of software engineering. Thrilled to share insights with the world. A Software engineering student.