FUNCTIONS
FUNCTIONS
FUNCTIONS
1. Function Declarations
In a function declaration, we must provide the function name, its return
type, and the number and type of its parameters. A function declaration
tells the compiler that there is a function with the given name defined
somewhere else in the program.
Syntax
return_type name_of_the_function (parameter_1, parameter_2);
2. Defining a function:
3. Calling the function: Calling the function is a step where we call the
function by passing the arguments in the function.
Types of Functions
1. Library Functions
Library Function
Example-
// C program to show user-defined functions
#include <stdio.h>
return a + b;
int main()
// function call
int res = sum(a, b);
return 0;
Output-
Sum is:70
The data passed when the function is being invoked is known as the
Actual parameters. In the below program, 10 and 30 are known as actual
parameters. Formal Parameters are the variable and the data type as
mentioned in the function declaration. In the below program, a and b are
known as formal parameters.
1. Pass by Value
2. Pass by Reference
1. Pass by Value
Example:
// C program to show use of call by value
#include <stdio.h>
var1 = var2;
var2 = temp;
int main()
var1, var2);
swap(var1, var2);
var1, var2);
return 0;
Output
2. Pass by Reference
The caller’s actual parameters and the function’s actual parameters refer
to the same locations, so any changes made inside the function are
reflected in the caller’s actual parameters.
Example:
#include <stdio.h>
*var1 = *var2;
*var2 = temp;
int main()
var1, var2);
swap(&var1, &var2);
var1, var2);
return 0;
Output
Advantages of Functions
1. The function can reduce the repetition of the same statements in the
program.
5. Once the function is declared you can just use it without thinking
about the internal working of the function.
Disadvantages of Functions
Scope of a Variable:-
The scope of a variable in a program defines where and for how long that
variable is valid and accessible. In essence, it sets the boundaries within
which the variable can be utilized.
o They have a broader scope and are visible in every part of the
program.
#include <stdio.h>
void display() {
printf("%d\n", global);
int main() {
display();
global = 10;
display();
return 0;
Output:
o Local variables are visible only within the block they are
declared in and any nested blocks inside that block.
o Example:
#include <stdio.h>
int main() {
{
int y = 40;
x++;
y++;
return 0;
Output:
x = 10, y = 20
x = 11, y = 41
x = 11, y = 20
Automatically initialized
Default Contains garbage value
to 0 if not explicitly
Initialization if not explicitly initialized
initialized