Call by value in C

I am new to programming and I am currently working on C.

I found out that C doesn't have a call by reference. The programs we write to pass the address of actual parameters to formal parameters are also called by a value in C.

Correct me if I am wrong. However, I ran this program:

// Swap two numbers using functions. #include

void swap(int *,int *);

void main()
{
    int x,y;
    printf ("Enter the values of x and y : ");
    scanf("%d %d",&x,&y);

    swap(x,y);

    printf("The value of x = %d and y = %d",x,y);
}

void swap(int *a,int *b)
{
    int temp;

    temp=*b;
    *b=*a;
    *a=temp;
}

      

It compiles just fine. However, I am getting a segmentation error in the output.

It asks me to enter the X and Y value and then it will throw a segmentation fault.

Please, help!!

+3


source to share


4 answers


you are dispatching to a int

function waiting int*

, so on dereference - temp=*b;

you are trying to access the memory you have -> segfault. Call swap

like this:swap(&x,&y);



+6


source


So close

swap(&x,&y);

      



You haven't missed links (pointers)

+5


source


To avoid such segfaults at runtime, always compile with -Wall

.

Actually, there is a way to pass by reference in C, just change the two lines in your code like this:

#define swap(x,y)  swap_impl__(&(x), &(y))

static void swap_impl__(int *a, int *b)
{
    int temp;
    temp=*b;
    *b=*a;
    *a=temp;
}

void main()
{
    int x,y;
    printf ("Enter the values of x and y : ");
    scanf("%d %d",&x,&y);

    swap(x,y);

    printf("The value of x = %d and y = %d",x,y);
}

      

+1


source


the call-by-value method of passing arguments to a function copies the actual value of the argument into the formal parameter of the function. In this case, changes made to the parameter inside the function do not affect the argument. but here you are passing values

swap(x,y)

      

but taking it as an address

void swap(int *a,int *b)

so it looks for the address that is passed to your variable. for example if you passed something like

swap(x,y)

and if we have x=100 and y=200

, then 100 and 200 are assumed to be addresses and trying to access it will definitely give you an error as they might be missing or garbage-meaningful.

0


source







All Articles