Definition of Function in C

  • function in C is a sub-program that has a group of statements/blocks of codes that together perform a specific task.
  • To make programming simple and easy to debug, we break a larger complex program into smaller & simpler sub-programs with a specific name that perform ‘well-defined tasks’ when use/call in the program once/more than once. These sub-programs are called functions.
  • A function in C is a self-contained block of executable code that can be called from any other function. In many programs, a set of statements is to be executed repeatedly at various places in the program and may with different sets of data.

Characteristics/Features of Functions

  • function declaration tells the compiler about a function’s name, return type, and parameters.
  • Once a function in C is defined, it can be used over and over and over again.
  • A single function can be used in several different and separate programs as per use that represent its reusability feature.
  • When a function is called, the control transfers to the called function from the calling function, which will be executed, and then finally transfers the control back to the calling function (to the statement following the function call).
  • Functions can share data by passing arguments and returning values.
  • Normally a function is identified by the ( ) symbol attached to it for parameters.
  • Functions in C programming are considered basic building blocks of the program. All C programs are written using library or UDF functions to improve the re-usability, and understandability, and to keep track of them.
  • Every C program has at least one function, which is main().
  • A function is used for dividing a large code into modules, due to this we can easily debug and maintain the code.
  • A function is a name for an action.
  • Unlike normal pointers, a Function Pointer points to code, not data. Typically a function pointer stores the start of executable code. Unlike normal pointers, we do not allocate/   de-allocate memory using function pointers. A function’s name can also be used to get a function’s address.
  • It makes a program modular i.e. functions are very important tools for Modular Programming, where we break large programs into small sub-programs or modules.
  • Static Function –  A function, which has a function definition prefixed with a static keyword is defined as a static function. The static function should call within the same source code.

Syntax of Function

    • The syntax of a function is: –
return datatype functionname (list of arguments)
{
datatype declaration of the arguments;
executable statements;
return (expression);
}

where
• The return data type is the same as the data type of the variable that is returned by the function using the return statement.
• A functionname is formed in the same way as variable names/identifiers are formed.
• list of arguments or parameters are valid variable names, separated by                       commas: (such as datatype1 var1, data type2 var2, …….. data type n var n)
for example (int x, float y, char z).
• Arguments give the values which are passed from the calling function.
• The body of the function contains the main executable statements.
• return statement returns a single value to the calling function.

    • Function Declaration –  Every function has its declaration and function definition. In function declaration only, only the function name, its argument list, and return type are specified and the function body or definition is not attached to it. The syntax of a function declaration is:-
return datatype functionname(list of arguments);
  For example,
int square(int num);
float temp(float c, float f);
    • Function Prototype –
      • Generally, prototype is an early sample of a product that serves as a basis for a future model. The term prototype is used in various contexts such as semantics, design, electronics, and software programming. Prototyping also provides specifications for a real working system rather than a theoretical one.
      • A prototype function is a declaration of a function with the following information to the compiler –
        • Name of the function.
        • The return type of the function.
        • Parameters list of the function.
      • The prototype of a function is also called the signature of the function.
      • A function prototype is simply the declaration of a function that contains the function’s name, parameters, and return type.
      • It doesn’t contain a function body/code of function.
      • A function prototype mainly gives information to the compiler that a function may later be used in the program with a certain name, parameter, and return type.
      • function prototype specifies the input/output interface to the function i.e. what to give to the function and what to expect from the function.
      • It is not necessary to declare a prototype specifically for a function but to properly call a function in C the function must be declared with a prototype before the point of the call.
      • It helps the compiler determine whether a function is called correctly or not. Each time when a function is called, its calling statement is compared with its prototype. In case of any mismatch, the compiler reports an error.
      • The function prototype is normally used at the beginning of the code for the function.

Advantage of Function

  • Avoid repetition of codes.
  • Increases program readability.
  • Divide a complex program into simpler ones.
  • It can be called any number of times in any place with different
    parameters.
  • Reduces chances of error.
  • Easy to write a correct small function
  • Easy to read, debug, and maintain a function’s code.
  • Modification in the program becomes easier by using a function.
  • Functions keep the program organized, and easy to understand, reduce complexity, make programming simple and easy to understand, and make it reusable.
  • The size of the program becomes comparatively small.
  • Program execution becomes comparatively fast.
  • Duplicate sets of statements are replaced by function calls.

Disadvantage of Function

  • Not suitable for simple, non-repetitive, small programs.
  • Each function takes a little bit more time and stack space to set up the call and return from the call.
  • The complexity of the program increases.
  • Program execution speed decreases.
  • It requires a programmer must be an expert in programming.
  • Normally a function doesn’t return more than one value at a time(i.e. it returns only one value at a time).it needs a pointer to return multiple values.

Return Statement

  • In C, the return statement is used to exit a function and optionally return a value to the caller.
  • The format and behavior of the return statement can vary based on the function’s return type and what we want to return.
  • In other words, if a function has to return an output value to the calling function, it is done through the return statement.
  • It may be possible that a function does not return any value rather only the control is transferred to the calling function.
  • The syntax for the return statement is:
    return (expression);
  • Examples are –
return (5);
return (x*y);
  • We can pass any number of arguments to a function but can return only one value at a time.
  • If a function does not return anything, a void specifier is used in the function declaration.
  • All the function’s return type is by default “int”, i.e. a function returns an integer value if no type specifier is used in the function declaration. To return customized datatype values (such as float, double, etc), the particular datatype specifier is used in the function declaration.
  • We can return all the data types from a function (but only one at a time). For this, the only condition is that the value returned using the return statement and the type specifier used in the function declaration should match completely.
  • A function in C can have more than one return statement. This happens mainly when we use the if-else/nested if-else type of code in our program.
  • When the execution of the return statement occurs, the control is transferred to the calling function with the value associated with it. All the remaining executable statements in the function will not be executed after this return.
  • Each format serves a different purpose depending on the function’s requirements and the data type being returned. These options give C functions flexibility in returning values and managing program flow effectively.
  • There are several formats of return statements. These are –
    • return :
      • When a function is declared with a void return type, it does not return any value and is represented with only the return keyword.
      • return; can still be used to exit the function early, but no value follows it.
      • for example –
void printMessage()
{
printf(“Hello, India!\n”);
return;       // Just exits the function and no value is returned
}
    • return 0 :
      • This statement typically signifies that the program has successfully completed its execution without any errors.
      • By convention, most operating systems interpret a return value  0 from the main function as successful completion.
      • It’s commonly used when there are no issues or errors during the execution of the program.
    • return 1 :
      • This statement generally indicates that the program encountered an error or did not complete as expected.
      • In many operating systems, any non-zero value is considered an error code. While 1 is commonly used to indicate a general error, other non-zero values (like 2, -1, etc.) can be used to indicate specific types of errors.
      • It’s often used when an error condition has been detected and the program needs to exit with a signal of failure.
    • return literal_value :
      • It is the simplest form of return is to return a literal value (like an integer, float, or character).
      • This is common in functions with a specific return type (e.g., int, float, char).
      • for example –
int getNumber()
{
      return 5;      // Returns an integer literal
}
char getChar()
{
      return ‘A’;     // Returns a character literal
}
float getFloat()
{
       return 3.14f;    // Returns a float literal
}
    • return expression :
      • A return statement can also return the result of an expression, such as an arithmetic or logical expression.
      • The expression is evaluated first, and the resulting value is returned.
      • for example –
int add(int a, int b)
{
return a + b;         // Returns the sum of a and b
}
int isEven(int number)
{
return number % 2 == 0; // Returns 1 if even, 0 if odd
}
    • return variable :
      • Using a return statement, we can also return the value stored in a variable directly.
      • This is especially useful when working with data that needs to be computed or modified within the function before returning.
      • for example –
int getResult()
{
int result = 42;
return result;       // Returns the value of the result
}
    • return pointer :
      • Functions that return pointers use the return statement to return the address of a variable, an allocated memory location, or the result of a computation.
      • For example –
(I)
int* getPointerToStaticVariable()
{
static int x = 10;
return &x;        // Returns the address of static variable x.
}
(II)
int* allocateMemory()
{
int *p = (int*) malloc(sizeof(int) * 5); // Dynamically allocated memory
if (p == NULL)
{
return NULL; // Returns NULL if allocation fails
}
return p; // Returns pointer with the allocated memory address
}
    • return array :
      • In C, we can’t return arrays directly, but you can return pointers to arrays, often by dynamically allocating memory for the array inside the function.
      • Alternatively, we can modify an array passed as a parameter to the function.
      • for example –
int* createArray(int size)
{
int *arr = (int*) malloc(sizeof(int) * size);
if (arr == NULL)
{
return NULL;        // Returns NULL if allocation fails
}
for (int i = 0; i < size; i++)
{
arr[i] = i + 1;
}
return arr;      // Returns pointer to the allocated array
}
    • return structure :
      • In C, functions can return entire structures by value. This allows us to return multiple values wrapped in a single structure.
      • for example –
struct Point
{
int x;
int y;
};
struct Point createPoint(int x, int y)
{
struct Point p;
p.x = x;
p.y = y;
return p;      // Returns a structure
}

Arguments/Parameters (Difference between Arguments and Parameters)

    • There are two types of arguments normally seen in a function :
      a) Actual arguments and  b) Formal arguments
    • The arguments defined inside the calling function in the main method is called Actual Arguments. In other words, when values are passed to the body of a function during a function call, they are actual arguments.
    • The arguments defined inside the body of function located usually outside the main method is called Formal Arguments.
    • The actual and formal arguments must match in type, order, and number for proper functioning of a function having parameters.
    • There are two ways to pass parameters in C – (i) Call by Value (ii) Call by Reference

(i)Call by Value 

    • Call by value method copies the value of an argument into the formal parameter of that function.
    • In call by value method, a copy of the variable is passed.
    • By default, C programming uses call-by-value to pass arguments.
  • Advantages : 
    • This mechanism is simple and it reduces confusion and complexity about the function use.

Disadvantages :

    • In this, there is a separate memory allocation for each of the variables, so unnecessary utilization of memory takes place.
    • In this, any changes made in the arguments are not reflected in the calling function, as these arguments are local to the called function and are destroyed with function return.

(ii)Call by Reference

    • Call by reference method copies the address of an argument into the formal parameter.
    • In call by reference method, a variable itself is passed.
    • The call-by-reference method is using pointers, so there is no doubling of the memory used by the variables.
    • References allow a function to change the value of the argument, which is sometimes useful. 

(Difference between Call by Value and Call by Reference)

Types of Function

  • There are two types of functions in C based on arguments passed and output return. These are –
    • In Built/Built In/System Defined/Library Functions
      • Library functions in C language are inbuilt functions that are grouped and placed in a common place and a single file name with file extension .h called library function.
      • Each library function in C performs a specific operation.
      • We can make only use of these library functions to get the pre-defined output instead of writing our own code to get those outputs.
      • It has already come with C software, no need to re-create it again rather only use it i.e. this type of function is already built into an application and can be accessed by end-users using proper syntax.
      • These functions are available in many library files. These files are accessed by the user in the program by including those header files with # include keyword (such as #include<stdio.h> etc.) in the program code at the top position before it was used.
      • The header file is a pointer/reference to the library that links those library header files with the program which can be searched and read by the compiler for used functions in the program.
      • These Library functions include several standard input/output (stdio.h), string manipulation (string.h), math functions (math.h), and date and time functions (time.h), etc.
      • They may be of four types/nature. These are –
        1. Function with No/Without Arguments No/Without Return
        2. Function with No/Without Arguments with Return
        3. Function with Arguments No/Without Return
        4. Function with Arguments with Return
      • For examples –
        • stdio.h library file contains printf(), scanf() functions etc.
        • conio .h library file contains clrscr(), getch() functions etc.
        • string.h library file contains strlen(), strupr(), strlwr(), strrev(), strcpy(), strcmp() functions etc.
        • math.h library file contains sqrt(), pow(), functions etc.
    • User Defined Functions (UDF)
      • User-defined functions help to decompose a large complex program into small simple segments customized which makes the program easy to understand, maintain, and debug.
      • In C programming Language main() function is user-implemented (user-defined) whose declaration is fixed in the compiler. hence we can say that main() is predefined and user-defined too because the programmer has to write the function’s body. The main() function is the function from where the execution of any C program begins first of all. So, the main() function is a mandatory part and function for any C program.
      • C allows us to define functions according to our needs. These functions are known as user-defined functions.
      • This function can be created and customized to include those required codes in the program as per the user’s need and execute when needed by calling that function.
      • They are also further created into four forms. These are –
        1. Function with No/Without Arguments No/Without Return
        2. Function with No/Without Arguments with Return
        3. Function with Arguments No/Without Return
        4. Function with Arguments with Return

(i)Function with No(Without)Arguments No(Without) Return Value :

        • A function that has no arguments and does not return any values to the calling function falls in this category.
        • These types of functions are confined to themselves i.e. neither do they receive any data from the calling function nor do they transfer any data to the calling function. So there is no data communication between the calling and the called function are only program control will be transferred.

(ii)Function with No(Without) Arguments With Return Value :

        • When a function does not receive any data from the calling function but does send some output value to the calling function, then it falls in this category.

(iii)Function With Arguments No(Without) Return Value :

        • When a function includes arguments but does not return anything, it falls into this category.
        • It is a one-way communication that takes place between the calling and the called function.

(iv)Function With Arguments With Return Value :

        • In this category, two-way communication takes place between the calling and called function i.e. a function returns an output value and also arguments are passed to it.

Types of Variables & Storage Classes

    • The storage class associated with a variable can sometimes be established by the location of the variable declaration within the program or by prefixing keywords to variable declarations.
    • There are 4 different types of variables/storage classes associated with the functions. These are –
      1. Automatic/Auto/Local/Private Variables
      2. External/Extern/Global/Universal Variables
      3. Static Variables
      4. Register Variables

For example:

auto int a, b;
static int a, b;
extern float f;

      • Automatic Variables :
        • When the variables are declared within the function of a program i.e. local to a function are called automatic variables.
        • The scope of variables lies within the function itself.
        • The automatic variables are defined in different functions, having the same name, but are treated as having different/different meanings.
        • It is the default storage class for variables declared in a function.
        • The auto variable is optional therefore there is no need to write auto before the variable name.
        • All the formal arguments in a function belong to the auto-storage class.
        • The initialization of the auto-variables is done by declarations or using assignment expressions in a function. If not initialized the unpredictable/garbage value is defined.
        • The value is not retained after exiting from the program i.e. volatile.
      • External Variables
        • When the variables are declared outside to all the functions of that program i.e. global to the function are called external variables.
        • These are not confined to a single function.
        • Their scope ranges from the point of declaration to the entire remaining program. Therefore, their scope may be the entire program or two or more functions depending upon where they are declared.
        • These are global and can be accessed by any function within its scope/range. Therefore value assigned by one function is available for another.
        • It allocates storage space required only when an external variable is defined.
        • Initial values can be assigned i.e. External variables can be assigned initial values as a part of variable definitions, but the values must be constants rather than expressions.
        • The external keyword/specifier is not required in external variables. definition.
        • A declaration is required if the external variable definition comes after the function definition. A declaration begins with an external specifier.
        • If an initial value is not included then it is automatically assigned a value of zero.
      • Static Variables
        • Static variables retain/never change their values throughout the execution of the program i.e. works on their previous values.
        • In the case of single file programs, static variables are defined within functions and individually have the same scope as automatic variables.
        • The keyword/specifier precedes the variable declaration.
        • Static values cannot be accessed outside of their defining function.
        • The static variables may have the same name as that of external variables but the local variables take precedence in the function. Therefore, external variables maintain their independence with locally defined auto and static variables.
        • Here, the initial value is expressed as the constant and not the expression.
        • Zeros are assigned to all static variables whose declarations do not include explicit initial values. Hence they always have assigned values.
        • Initialization is done only in the first execution.
      • Register Variables
        • Registers are special storage areas within a computer’s CPU.
        • All the arithmetic and logical operations are carried out with these registers.
        • For the same program, the execution time can be reduced if certain values can be stored in registers rather than memory.
        • These programs are smaller in size (as few instructions are required) and few data transfers are required.
        • They are declared by the proceeding declaration by ‘register’ reserved word such as register int m; .
        • These variables are stored in the registers of computers. If the registers are not available they are put in memory.
        • Usually 2 or 3 register variables are there in the program.
        • The scope is the same as an automatic variable, local to a function in which they are declared.
        • Address operator ‘&’ cannot be applied to a register variable.
        • If the register is not available the variable is thought to be like the automatic variable.
        • Usually associated/used integer variable but with other types, it is allowed to have the same size (short or unsigned).
        • It can be formal arguments in functions.
        • Pointers to register variables are not allowed i.e. pointer does not store the address of the register variable.
        • These variables can be used for loop indices also to increase efficiency.

Recursion

  • When a function calls itself within its body again for processing, the process is known as ‘Recursion’ and that function is known as a ‘Recursive function’.
  • Recursion is the process of defining something in terms of itself.
  • When a function calls itself, new local variables and parameters are allocated storage on the stack and the function code is executed with these new variables from the start. A recursive call does not make a new copy of the function. Only the arguments and variables are new. As each recursive call returns, the old local variables and parameters are removed from the stack and execution resumes at the point of the function call inside the function.
  • For a proper recursion function, every “recursive function” must have a terminating condition.
  • When we write recursive functions, it must have an exit condition somewhere to force the function to return without the recursive call being executed. If we do not have an exit condition in the program, the recursive function will recurse forever until we run out of stack space and indicate an error about lack of memory, or stack overflow.
  • Based on recursion, a function or program may be divided into two categories –
    • Recursive Program/Non-Iterative Program – A program with recursion (code) is known as Recursive Program.
    • Non-recursive Program/Iterative Program – A program without recursion (code) is known as a Non-recursive Program.
  • A recursive function first proceeds towards the innermost condition, which is the termination condition, and then returns with the value to the outermost call and produces a result with the values from the previous return.
  • This mechanism applies only to those programs/problems, that repeat themselves.
  • These types of problems can be implemented either through loops or recursive functions.
  • A recursive function exists in two phases –
    1. Winding phase
    2. Unwinding phase

    Winding phase : When the recursive function calls itself, and this phase ends when the condition is reached.

    Unwinding phase : Unwinding phase starts when the condition is reached, and the control returns to the original call.

  • It is costly in terms of time and space.

Loading

Categories: C

0 Comments

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.