Functions in C

functions

Functions in C

Function is a set of statements that performs some specific task or operation.

When we need to repeat the same task in program, instead of writing same code again and again, we call the function.


Syntax

        
return_type function_name(parameters)  {
    //Function statements
}   
        
    

Need of function

1. To improve the readability of code.

2. Improve the reusability of code.

3. Reduce the size of code.

4. Same function can be use in any program rather than writing the same code again and again.


Function declaration

A function declaration provides the following information to the compiler.

1. The name of function

2. The type of value returned.

3. The number and type of arguments that must be supplied in a call to the function.

Example

        
int sum(int, int);
int fun(char, int);
int area(float, float); 
        
    

Function definition

The function definition is similar to the function declaration but does not have the semicolon. The first line of the function definition is called a function declarator. This is followed by the function body. It is composed of the statements that make up the function, delimited by the braces.

Example

        
int sum(int a, int b)  {
    //Function statements
}   
        
    

Function call

A function is a dormant entity, which comes to life when a call is made to the function. A function call is specified by the function name followed by the values of the parameters enclosed within parentheses, terminated by a semicolon ;.

Function can be call by two methods.

1. Call by value

2. Call by reference

Call by value

The call by value method of passing arguments to a function copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument. By default, C programming uses call by value to pass arguments. In general, it means the code within a function cannot alter the arguments used to call the function.


Call by reference

The call by reference method of passing arguments to a function copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. It means the changes made to the parameter affect the passed argument.




Join Our Social Media Connections

Post a Comment

0 Comments