Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does C even have "pass by reference"? [duplicate]

Tags:

c

pointers

I heard that in "c" that there are we can pass the arguments via "call by value" or "call by reference". But in one book it's mentioned that there are we can pass the arguments via both way but there is no "pass by reference" but I actually pass the mostly arguments by "pass by reference".

So why it is mentioned "does C even have "pass by reference"?

A detailed description will be greatly appreciated.

like image 370
Varun Chhangani Avatar asked Jun 18 '13 12:06

Varun Chhangani


2 Answers

C parameters are always passed by value rather than by reference. However, if you think of the address of an object as being a reference to that object then you can pass that reference by value. For example:

void foo(int *x)
{
    *x = 666;
}

You ask in a comment:

So why do we need pointers in C when we can pass all the parameters by value?

Because in a language that only supports pass-by-value, lack of pointers would be limiting. It would mean that you could not write a function like this:

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

In Java for example, it is not possible to write that function because it only has pass-by-value and has no pointers.

In C++ you would write the function using references like this:

void swap(int &a, int &b)
{
    int temp = a;
    b = a;
    a = temp;
}

And similarly in C#:

void swap(ref int a, ref int b)
{
    int temp = a;
    b = a;
    a = temp;
}
like image 109
David Heffernan Avatar answered Sep 20 '22 05:09

David Heffernan


The concept of "reference semantics" is an abstract, theoretical one, meaning that you have a way for a function to modify existing data in place by giving that function a reference to the data.

The question is whether reference semantics can be implemented by a language. In C, you can obtain reference semantics by using pointers. That means you can obtain the desired behaviour, but you need to assemble it yourself from various bits and pieces (pointer types, address-of operators, dereference operators, passing pointers as function arguments ("by value")).

By contrast, C++ contains a native reference type and thus implements reference semantics directly in the language.

Other languages have different approaches to this, for example, in Python many things are references by default (and there's a difference, say, between a = b and a = b[:] when b is a list). Whether and how a language provides reference vs value semantics is a profound part of the language's design.

like image 31
Kerrek SB Avatar answered Sep 21 '22 05:09

Kerrek SB