Circular Shift of numbers by function

45 Views Asked by At

I am writting a program to shift the numbers entered in a circular manner which i know how to by using call by value , but i am unable to the logic in call by refrence way

This is the code:

#include<stdio.h>
int shift(int *a, int *b, int *c);
void main()
{
    int x, y, z;

    printf("Enter x: ");
    scanf("%d", &x);
    printf("Enter y: ");
    scanf("%d", &y);
    printf("Enter z: ");
    scanf("%d", &z);

    printf("Before Shift: x: %d\ty: %d\t z: %d",x,y,z);
    //call the shift function
    shift(&x, &y, &z);
    printf("\n After Shift: x: %d\ty: %d\t z: %d",x,y,z);
}
int shift(int *a, int *b, int *c)
{
    int temp;
    temp = *c;
    *c = *b;
    *b = *a;
    *a = temp;
}

here in the last part of the code,what are the exact meaning of the shift function and how is here the address is moving from one variable to another.

1

There are 1 best solutions below

0
Neil On

In C, variables are passed-by-value into functions. See What's the difference between passing by reference vs. passing by value? Specifically, let us re-write the programme for illustrative purposes.

#include <stdio.h>
static void fail(int t, int u, int v)
    { int temp; temp = v; v = u; u = t; t = temp; }
static void shift(int *a, int *b, int *c)
    { int temp; temp = *c; *c = *b; *b = *a; *a = temp; }
int main(void) {
    int x = 1, y = 2, z = 3;
    printf("Before: x: %d\ty: %d\t z: %d\n",x,y,z);
    fail(x, y, z);
    printf("fail:   x: %d\ty: %d\t z: %d\n",x,y,z);
    shift(&x, &y, &z);
    printf("shift:  x: %d\ty: %d\t z: %d\n",x,y,z);
}

The call to fail from main copies the values (x, y, z) to (t, u, v). (t, u, v) are permuted, but then destroyed when the function goes out of scope and fail returns to main. The original values are unchanged.

Graphical layout of the data from the programme.

The programme then calls shift from main with the addresses of (&x, &y, &z) passed to (a, b, c); dereferencing (*a, *b, *c) in shift is (x, y, z) in main. The variables are correctly permuted.