C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Pointers in C

Pointer and function (call by reference)

C Program: Call by Reference using Pointers

C

#include <stdio.h>

 

// Function to swap two numbers using call by reference

void swap(int *x, int *y) {

    int temp;

    temp = *x;  // store value at address of x

    *x = *y;    // put y's value into x

    *y = temp;  // put x's value into y

}

 

int main() {

    int a, b;

 

    printf("Enter two numbers: ");

    scanf("%d %d", &a, &b);

 

    printf("\nBefore swapping: a = %d, b = %d\n", a, b);

 

    // Function call by reference

    swap(&a, &b);

 

    printf("After swapping:  a = %d, b = %d\n", a, b);

 

    return 0;

}

Output

 
OUTPUT :
Enter two numbers: 10 20

Before swapping: a = 10, b = 20
After swapping:  a = 20, b = 10

Explanation

Concept

Description

void swap(int *x, int *y)

Function takes addresses of variables, not copies.

*x and *y

Dereferencing to access the actual values stored at those addresses.

swap(&a, &b)

Passes the addresses of a and b from main().

Changes

Inside the function directly affect the original variables.