#include <stdlib.h>
int swap(int a,int b);
int main() {
int x,y;
printf("Enter the first integer:"); scanf("%d",&x);
printf("Enter the second integer:"); scanf("%d",&y);
printf("\nBefore swap: x=%d, y=%d\n",x,y);
swap(x,y);
printf("After swap: x=%d, y=%d",x,y);
return 0;
}
int swap(int a, int b){
int temp;
temp = a;
a=b;
b=temp;
}
This is my code to swap 2 integers entered by the user but it doesn't work although everything seems to be in order. However if I change my code to this using pointers, it does.
#include <stdlib.h>
int swap(int *,int *);
int main() {
int x,y;
printf("Enter the first integer:"); scanf("%d",&x);
printf("Enter the second integer:"); scanf("%d",&y);
printf("\nBefore swap: x=%d, y=%d\n",x,y);
swap(&x,&y);
printf("After swap: x=%d, y=%d",x,y);
return 0;
}
int swap(int *a, int *b){
int temp;
temp = *a;
*a=*b;
*b=temp;
}
I would really appreciate if anyone could explain me why and how it worked with pointers but why it didn't without pointers.
The first function that shall have the return type void because it returns nothing
deals with copies of values of expressions used as arguments.
You can imagine the function definition and its call the following way
That is within the function there are swapped the function local variables
a
andb
. The original variablesx
andy
declared in main stay unchanged.In the second function definition the arguments
x
andy
are passed to the function by referenceIn C passing by reference means passing objects indirectly through pointers to them.
From the C Standard (6.2.5 Types, p. #20)
So dereferencing the pointers (that themselves are passed by value) you get a direct access to the pointed objects that are changed within the function