Functions

By Paribesh Sapkota

Definition:

A function is a block of code/group of statements/self contained block of statements/ basic building blocks in a program that performs a particular task. It is also known as procedure or subroutine or module, in other programming languages.

To perform any task, we can create function. A function can be called many times. It provides modularity and code reusability.

Advantage of functions

  • Code Reusability

By creating functions in C, you can call it many times. So we don’t need to write the same code again and again.

  • Code optimization

It makes the code optimized we don’t need

  • Easily to debug the program.

Types of Functions

There are two types of functions in C programming:

Library Functions: are the functions which are declared in the C header files such as scanf(), printf(), gets(), puts(), ceil(), floor() etc. You just need to include appropriate header files to use these functions. These are already declared and defined in C libraries. points to be Remembered

System defined functions are declared in header files

System defined functions are implemented in .dll files. (DLL stands for Dynamic Link Library).

To use system defined functions the respective header file must be included.

User-defined functions: are the functions which are created by the C programmer, so that he/she can use it many times. It reduces complexity of a big program and optimizes the code. Depending upon the complexity and requirement of the program, you can create as many user-defined functions as you want.

ELEMENTS OF USER-DEFINED FUNCTIONS :

To use a user-defined function, we first have to understand the different parts of its syntax. The user-defined function in C can be divided into three parts:

  1. Function Prototype
  2. Function Definition
  3. Function Call

C Function Prototype

A function prototype is also known as a function declaration which specifies the function’s name, function parameters, and return type. The function prototype does not contain the body of the function.  It is basically used to inform the compiler about the existence of the user-defined function which can be used in the later part of the program.

Syntax

return_type

function_name

(type1 arg1, type2 arg2, ... typeN argN);

We can also skip the name of the arguments in the function prototype. So,

return_type

function_name

(type1 , type2 , ... typeN);

C Function Definition

Once the function has been called, the function definition contains the actual statements that will be executed. All the statements of the function definition are enclosed within { } braces.

Syntax

return_type

function_name

 (type1 arg1, type2 arg2 .... typeN argN) {

    // actual statements to be executed
    // return value if any
}

Note: If the function call is present after the function definition, we can skip the function prototype part and directly define the function.

C Function Call

In order to transfer control to a user-defined function, we need to call it. Functions are called using their names followed by round brackets. Their arguments are passed inside the brackets.

Syntax

function_name(arg1, arg2, ... argN);

Example of User-Defined Function

The following C program illustrates how to use user-defined functions in our program.

// C Program to illustrate the use of user-defined function
#include <stdio.h>
 
// Function prototype
int sum(int, int);
 
// Function definition
int sum(int x, int y)
{
    int sum;
    sum = x + y;
    return x + y;
}
 
// Driver code
int main()
{
    int x = 10, y = 11;
 
    // Function call
    int result = sum(x, y);
    printf("Sum of %d and %d = %d ", x, y, result);
 
    return 0;
}

Output

Sum of 10 and 11 = 21

Components of Function Definition

There are three components of the function definition:

  1. Function Parameters
  2. Function Body
  3. Return Value

1. Function Parameters

Function parameters (also known as arguments) are the values that are passed to the called function by the caller. We can pass none or any number of function parameters to the function.

We have to define the function name and its type in the function definition and we can only pass the same number and type of parameters in the function call.

Example

int foo (

int a, int b)

;

Here, a and are function parameters.

Note: C language provides a method using which we can pass variable number of arguments to the function. Such functions are called variadic function.

2. Function Body

The function body is the set of statements that are enclosed within { } braces. They are the statements that are executed when the function is called.

Example

int foo (int a, int b) {

int sum = a + b;


return sum;

}

Here, the statements between { and is function body.

3. Return Value

The return value is the value returned by the function to its caller. A function can only return a single value and it is optional. If no value is to be returned, the return type is defined as void.

The return keyword is used to return the value from a function.

Syntax

return

 (expression);

Example

int

foo (int a, int b) {

return a + b;

}

Passing Parameters to User-Defined Functions

We can pass parameters to a function in C using two methods:

  1. Call by Value
  2. Call by Reference

1. Call by value

In call by value, a copy of the value is passed to the function and changes that are made to the function are not reflected back to the values. Actual and formal arguments are created in different memory locations.

Example

// C program to show use of
// call by value
#include <stdio.h>
 
void swap(int a, int b)
{
    int temp = a;
    a = b;
    b = temp;
}
 
// Driver code
int main()
{
    int x = 10, y = 20;
    printf("Values of x and y before swap are: %d, %d\n", x,
           y);
    swap(x, y);
    printf("Values of x and y after swap are: %d, %d", x,
           y);
    return 0;
}

Output

Values of x and y before swap are: 10, 20
Values of x and y after swap are: 10, 20

scope visibility and lifetime of variables 

Scope, visibility, and lifetime of variables in C are closely interconnected concepts, yet each has distinct characteristics. Scope defines the area within a C program where a variable can be used. Visibility pertains to whether a variable can be accessed within a particular scope. Lifetime refers to the duration a variable remains in the system’s memory.

Let’s define the concepts of scope, visibility, and lifetime for a variable:

Scope refers to the region within a program where a variable can be used. Essentially, it is the section of code where the variable is accessible. There are four types of scope in C:
– File scope
– Block scope
– Function scope
– Prototype scope

Visibility of a variable denotes whether it can be accessed in a particular region of code or throughout the entire program.

Lifetime of a variable indicates the duration for which the variable occupies space in the system’s memory. It can be categorized into three types:
– Static lifetime
– Automatic lifetime
– Dynamic lifetime

Here are the four types of variable scope in C:

1. File Scope
Variables with file scope are accessible throughout the entire file or program. This means they have a global scope and can be used by every function and block within the program.

#include <stdio.h>

// variable with file scope
int x = 10;

void func() {
  // x is available in func() function,
  // x now equals 10 + 10 = 20
  x += 10;
  printf("Value of x is %d\n", x);
}

int main() {

  func();
  // x is also available in main() function
  x += 30; // x now equals 20 + 30 = 50
  printf("Value of x is %d", x);
  return 0;
}

Explanation : A global variable x is declared having file scope. main() function and func() function are able to access the variable x because it has file scope. In the code, first we have increased the value of x by 10 (x = 20 now) and then by 30 (x = 50 now), and we can see from the output that x preserves its value 20 after the changes made in the function func() because it has file scope.

2.Block Scope

Variables with block scope are limited to the block of code in which they are defined, which is enclosed in curly braces `{}`. These variables are not accessible outside this block, and their memory is released once the block’s execution is complete.

#include <stdio.h>

int main() {
  int a = 5;
  int b = 10;

  // inner block of code having block scope
  {
    int sum = a + b;
    printf("Sum of a and b: %d", sum);
  }

  // the below statement will throw an error because,
  // sum variable is not available outside the scope of above block,
  // printf("Sum of a and b: %d", sum);

  return 0;
}

Explanation : In the above program, the sum variable has block scope, we can’t access the sum variable outside this block where sum is declared. If we uncomment the printf(“Sum of a and b: %d”, sum); statement then the compiler will throw an error of undeclared sum variable in the current scope.

3. Function Scope
Variables with function scope are declared within a function and are accessible only within that function. Their scope begins with the opening curly brace `{` and ends with the closing curly brace `}` of the function. Memory for these variables is allocated when the function is called and is released when the function execution completes and returns a value, at which point the variables go out of scope and are removed from memory.

#include <stdio.h>

void findAge() {
  // the age variable is not accessible outside the function findAge() 
  // as it is having local scope to the function i.e. function scope
  int age = 18;
}

int main() {

  printf("Age is %d", age);
  return 0;
}

Explanation : We can see in the output that a compilation error is thrown to us because we are using an age variable outside the function from where it is declared. Compiler has thrown an error because age variable is not available outside the function as age variable only has function scope.

4. Function Prototype Scope
Variables with function prototype scope are declared as parameters in a function’s definition. Similar to function scope variables, these parameters are allocated memory when the function is called and are deleted once the function execution ends.

#include <stdio.h>

// variables a and b are available only inside the function and 
// both variables have function prototype scope
int findSum(int a, int b) {
  return a + b;
}

int main() {
  int sum = findSum(3, 5);
  printf("Sum of 3 and 5 is %d", sum);
  return 0;
}

Explanation : When the findSum() function is invoked, space for variables a and b is allocated in the system’s memory. Variables a and b are findSum() function parameters and these variables have function prototype scope, we can access these variables only in the function definition and not outside of it.

Local Variables

Variables declared within a function or an inner block are known as local variables. They are confined to the scope of that function or block and can only be used within that specific area.

#include <stdio.h>

int main() {
  int sum = 0;

  // inner block of code having block scope
  {
    int a = 5;
    int b = 10;
  }
  // this statement will throw an error because a and b are not available outside the above block of code
  sum = a + b;

  return 0;
}

Global Variables

Variables declared outside of all functions are known as global variables. These variables have file scope, meaning they can be accessed from anywhere in the program. They remain in memory for the entire duration of the program’s execution.

#include <stdio.h>

// global variable
int side = 10;

int main() {
  int squareArea = side * side;

  printf("Area of Square : %d", squareArea);

  return 0;
}

 

Important Questions
Comments
Discussion
0 Comments
  Loading . . .