Functions in C

05 min read

What is a function? It is a self-contained program segment that carries out some specific, well-defined task when called. There are two types of functions. They are:

1) Library or built-in functions: These functions are pre-defined. Users can only use these functions but cannot modify them. Users may not understand the internal working of these functions. It is enough if we know how to use them.

Ex: sqrt()

2) User-defined functions: Functions defined by the user according to their requirement. The user can modify these functions. Main function is also a user-defined function but the function name, number of arguments and argument types are defined by the language, although the statements inside it are specified by the user.

Ex: square(), cube() etc can be written as user-defined functions.

 

Advantages of using functions:

  1. Avoids repetition of the code.
  2. Increases reusability i.e., existing code can be used rather than trying to develop new code. Also, the function can be used by many other programs.
  3. The length of the source code (ie., the program size) is reduced.
  4. Easy to debug.
  5. Increases readability.
  6. Program development time, effort and cost can be reduced.

 

To write programs using functions, we must know about the following three:

 

a) Function definition: It as two parts namely function header and function body.

Syntax:

[ReturnType] FunctionName([type argl ,type arg2,       , type argN])

{

[ local declarations; ]

function body;

[ return (expression); ]

}

 

b) Function call:  This statement should appear in the calling function. It is given by writing the function name followed by an optional list of parametersenclosed within parenthesis and finally terminated by a ';' semicolon. In function call, the data type of the parameters is not needed.

Syntax

functionName(argl, arg2, ................argn);  //function which does not return any value.

X = functionName(argl, arg2,...............argn);  //function which returns a value.

(Or)

printf("%d",functionName(argl, arg2,.............argn));

 

c) Function Prototype or declaration: If main() calls user-defined functions which returns other than an integer value, those called functions should be defined before main(). Or, if these user-defined functions have to be defined after main(), then those functions should be declared before calling them. This function declaration is called function prototype.

Example:

float u_d1()
{
float f1 ;
return (f1);
}

int main()
{
u_d1();
}

or

float u_d1();
int main()
{
u_d1();
}

float u_d1()
{
float f1;
return(f1);
}


POST A NEW COMMENT
     
  • Input (stdin)

    Output (stdout)


    Input (stdin)

    Your Output (stdout)

    Expected Output

    Compiler Message

    Input (stdin)

    2    3

    Your Output (stdout)

    5

    Expected Output

    5

    Compiler Message

    5

    Error