Pass by Reference in C

This is a simple example on how to pass a value by reference.


#include <stdio.h>

void swap(int, int);

int main(void)
{
int x, y;
x = 10;
y = 20;
printf("x = %d y = %d\n", x, y)
swap(&x, &y);
printf("x = %d y = %d\n", x, y);
return 0;
}

void swap(int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}

result : x = 10 y = 20 x = 20  y = 10

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s