#include <stdio.h>
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
int main()
{
int x = 10, y = 20;
printf("Before swap: x = %d, y = %d\n", x, y);
swap(&x, &y);
printf("After swap: x = %d, y = %d\n", x, y);
return 0;
}
This program defines a function swap
that takes two pointers to integers as arguments. The function swaps the values of the two integers by using the pointers to modify the memory locations of the variables.
In the main
function, we declare two variables x
and y
, and pass their addresses to the swap
function. This allows the swap
function to modify the variables directly, rather than working with copies of their values.
When you run this program, it will output the following:
Before swap: x = 10, y = 20
After swap: x = 20, y = 10
0 Comments