#include<stdio.h>
int max(int
x,int y)
{
if(x>y)
return x;
else
return y;
}
int main()
{
int a=10;
int b=20;
int c=max(a,b);
printf("maximum is
%d",c);
return 0;
}
- C functions are used to avoid rewriting same logic/code again and again in a program.
- There is no limit in calling C functions to make use of same functionality wherever required.
- We can call functions any number of times in a program and from any place in a program.
- A large C program can easily be tracked when it is divided into functions.
- The core concept of C functions are, re-usability, dividing a big task into small pieces to achieve the functionality and to improve understandability of very large C programs.
Example Program For Parameters
in functions:-
#include<stdio.h>
//parameters
in funcitons
int fun(int
x)
{
x=20;
}
int main()
{
int x=20;
fun(x);
printf("x =%d",x);
return 0;
}
- Function declaration or prototype – This informs compiler about the function name, function parameters and return value’s data type.
- Function call – This calls the actual function
- Function definition – This contains all the statements to be executed.
C Function |
FUNCTION CALLING:
- In call by value method, the value of the variable is passed to the function as parameter.
- The value of the actual parameter can not be modified by formal parameter.
- Different Memory is allocated for both actual and formal parameters. Because, value of actual parameter is copied to formal parameter.
- Actual parameter – This is the argument which is used in function call.
- Formal parameter – This is the argument which is used in function definition.
Program For Call By Value:
// C
program to illustrate
// call by value
#include
<stdio.h>
// Function
Prototype
void
swapx(int x, int y);
// Main
function
int main()
{
int a = 10, b = 20;
// Pass by Values
swapx(a, b);
printf("a=%d b=%d\n", a,
b);
return 0;
}
// Swap
functions that swaps
// two
values
void
swapx(int x, int y)
{
int t;
t = x;
x = y;
y = t;
printf("x=%d y=%d\n", x,
y);
}
- In call by reference method, the address of the variable is passed to the function as parameter.
- The value of the actual parameter can be modified by formal parameter.
- Same memory is used for both actual and formal parameters since only address is used by both parameters.
Program For Call by Reference:-
// C
program to illustrate
// Call by
Reference
#include
<stdio.h>
// Function
Prototype
void
swapx(int*, int*);
// Main
function
int main()
{
int a = 10, b = 20;
// Pass reference
swapx(&a, &b);
printf("a=%d b=%d\n", a,
b);
return 0;
}
// Function
to swap two variables
// by
references
void
swapx(int* x, int* y)
{
int t;
t = *x;
*x = *y;
*y = t;
printf("x=%d y=%d\n",
*x, *y);
}
Comments
Post a Comment