Definition

  • function is a sub program that has group of statements/block 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 which perform ‘well defined tasks’ when use/call in the program once/more than once. These sub-programs are called functions.
  • A function is a self- contained block of executable code that can be called from any other function.In many programs, a set of statements are to be executed repeatedly at various places in the program and may with different sets of data.

Characteristics/Features

  • function declaration tells the compiler about a function’s name, return type, and parameters.
  • Once a function 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 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 shared data by passing arguments and returning values.
  • Normally a function is identified by ( ) symbol attached with it for parameters.
  • Functions in C programming are considered as basic building blocks of the program. All C programs are written using library or udf functions to improve the re-usability, understand ability and to keep track of them.
  • Every C program has at least one function, which is main().
  • Function are used for divide a large code into module, 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 functions‘ 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

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

where
• return data type is the same as the data type of the variable that is returned by           the function using return statement.
• 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.
• body of function contains 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.
      • 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.
      • Prototype of a function is also called signature of the function.
      • A function prototype is simply the declaration of a function that contains function’s name, parameters and return type.
      • It doesn’t contain 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 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 in order 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 in determining 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, compiler reports an error.
      • The function prototype is normally used at the beginning of the code for the function.

Advantage

  • 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 maintenance a function’s code.
  • Modification in program becomes easier by using function.
  • Functions keeps the program organized, easy to understand, reduces complexity, makes programming simple and easy to understand and makes it reusable.
  • The size of program becomes comparatively small.
  • Program execution becomes comparatively fast.
  • Duplicate set of statements are replaced by function calls.

Disadvantage

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

Return Statement

    • 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.
    • 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, void specifier is used in the function declaration.
    • All the function’s return type is by default is “int”, i.e. a function returns an integer value, if no type specifier is used in the function declaration.
    • To return customized datatype value (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 being that the value returned using return statement and the type specifier used in function declaration should match completely.
    • A function can have more than one return statements. This happens mainly when we use  if-else/nested if-else type of code in our program.
    • When the execution of 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 returning.

Arguments/Parameters 

    • There are two types of arguments normally seen in a function :
      a) Actual arguments and  b) Formal arguments
    • The arguments defined inside calling function in main method is called Actual Arguments.In other words, when values are passed to the body of function during function call, they are actual arguments.
    • The arguments defined inside 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 separate memory allocation for each of the variable, so unnecessary utilization of memory takes place.
    • In this, any changes made in the arguments are not reflected to 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. 

Types of Function

  • There are two types of function in C on the basis of arguments passed and output return. These are –
    • In Built/Built In/System Defined/Library Functions
      • Library functions in C language are inbuilt functions which are grouped together and placed in a common place and a single file name with file extension .h called library function.
      • Each library function in C performs 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 a number of libraries file. 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 file 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 customizly which makes 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 programmer has to write function’s body.The main() function is the function from where execution of any C program begins first of all. So, main() function is mandatory part and function for any C program.
      • C allows us to define functions according to our need. These functions are known as user-defined functions.
      • This function can be created and used customizely to include those required codes in the program as per 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 which has no arguments and does not return any values to the calling function, falls in this category.
        • These type 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 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 in this category.
        • It is one way communication 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 variables 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 defined in different functions, having same name, but are treated as different/different meaning.
        • 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 belongs to the auto storage class.
        • The initialization of the auto-variables is done by declarations or using assignment expression in a function.If not initialized the unpredictable/garbage value is defined.
        • The value is not retained after exit from the program i.e. volatile in nature.
      • 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 in nature 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 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 variable. definition.
        • A declaration is required if the external variable definition comes after the function definition.A declaration begins with an external specifier.
        • If initial value is not included then it is automatically assigned a value of zero.
      • Static Variables
        • Static variables retain/never changes their values throughout the execution of program i.e. works on their previous values.
        • In case of single file programs, static variables are defined within functions and individually have the same scope as automatic variables.
        • The keyword/specifier precedes with the variable declaration.
        • Static value cannot be accessed outside of their defining function.
        • The static variables may have 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, initial value is expressed as the constant and not 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 is 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 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.
        • Scope is same as 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 though to be like the automatic variable.
        • Usually associated/used integer variable but with other types it is allowed having 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 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 ‘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 writing recursive functions, it must have a 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 error about lack of memory, or stack overflow.
  • On the basis of recursion, a function or program may be divided into two category –
    • 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 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 result with the values from the previous return.
  • This mechanism applies only to those programs/problems, which repeats itself.
  • 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.

 548 total views,  1 views today

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.