Home functions Functions in C Programming Language
Functions in C Programming Language
Functions:
A function is a set of statements that take inputs, do some specific computation and produces output. The idea is to put some commonly or repeatedly done task together and make a function, so that instead of writing the same code again and again for different inputs, we can use the functions.
Example:-
#include <stdio.h>
void swap(int x,int y);
int main()
{
int a=2,b=10;
printf("Before Swapping a=%d and b=%d\n",a, b);
swap(a,b);
}
void swap(int x, int y)
{
int temp;
temp = x;
x = y;
y = temp;
printf("After Swapping a = %d and b = %d", x, y);
}
Here variable 'a' and 'b' have been passed to the function 'add' in the program, 'a' and 'b' are copied to the values 'x' and 'y' variable.
2. Call by reference:- In this method, the actual values are not passed, instead their addresses are passed. There is no copying of values since their memory locations are referenced. If any modification is made to the values in the called function, the original values get changed within the calling function.
For example:
#include <stdio.h>
void swap(int *x, int *y);
int main(){
int a = 5, b = 20;
printf("Before Swapping a = %d and b = %d\n", a, b);
swap(&a, &b);
}
void swap(int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
printf("After Swapping a = %d and b = %d", *x, *y);
}
Here the variable 'a' and 'b' address are passed to the function 'add' in the program, 'a' and 'b' are not copied to the values 'x' and 'y' variable.
It only holds the address hold of the variables.
VIDEO
1 Comments
Good post
ReplyDelete