C Tutorial
Arguments are generally passed to functions in any one of the two ways.
Each actual arguments in the calling function is copied into corresponding formal arguments of the called function.
So changes happened to the formal arguments in the called function have no effect on the values of the actual arguments.
#include <stdio.h> // Swap function declaration void swap(int, int); void main() { int a, b; printf("Enter a: "); scanf("%d", &a); printf("Enter b: "); scanf("%d", &b); printf("Before swap: a = %d, b = %d\n", a, b); swap(a, b); printf("After Swap: b = %d, b = %d\n", a, b); } //Swap function definition void swap(int a, int b) { int temp; temp = b; b = a; a = temp; }Output:
$ cc swap2.c $ ./a.out Enter a: 10 Enter b: 5 Before swap: a = 10, b = 5 After Swap: b = 10, b = 5
Address of the actual arguments in the calling function is copied into formal arguments in the called function.
Changes in formal arguments in the called function have effect in the actual arguments in the calling function.
#include<stdio.h> // Swap function declaration void swap(int*, int*); void main() { int a, b; printf("Enter a: "); scanf("%d", &a); printf("Enter b: "); scanf("%d", &b); printf("Before swap: a = %d, b = %d\n", a, b); swap(&a, &b); printf("After Swap: b = %d, b = %d\n", a, b); } //Swap function definition void swap(int *a, int *b) { int temp; temp = *b; *b = *a; *a = temp; }Output:
$ cc swap.c $ ./a.out Enter a: 34 Enter b: 54 Before swap: a = 34, b = 54 After Swap: b = 54, b = 34
C Tutorial
Privacy Policy | Copyright2020 - All Rights Reserved. | Contact us
| Report website issues in Github
| Facebook page
| Google+ page