0

I want to pass a value by reference in C. Are this two functions the same? Which is the difference? Is the same in C++?

void foo1(int * val1, int * val2)

void foo2(int &val1, int &val2)

Thanks,

dani
  • 341
  • 1
  • 7
  • 18
  • 1
    Duplicate of : http://stackoverflow.com/questions/596636/c-difference-between-ampersand-and-asterisk-in-function-method-declar – Rohan Prabhu Aug 07 '12 at 11:41

5 Answers5

4

References are C++ only (not C).

The implementations of the methods will be different, since dereferencing a reference is different from dereferencing a pointer in C++.

e.g.

ref.method();

vs.

ptr->method();

In both cases you're calling on the original object passed to the method, not a copy.

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
1

The second is not C, only C++. Passing by reference is in C emulated by passing the addresses of the values.

Daniel Fischer
  • 181,706
  • 17
  • 308
  • 431
1

In C you can not do foo2, because there is no reference operator like in C++. In C++ they are not the same either. References can not be NULL and they are constant. They can not point to another location after initialisation.

krase
  • 1,006
  • 7
  • 18
1

void foo1(int * val1, int * val2) is equivalent of void foo2(int &val1, int &val2) in C. In both the case functions need addresses.

The 2nd one is used in C++. This can be used to pass the reference of any variable.

For example if you have a variable like int num1 = 10, num2 = 20; .

Then foo2(&num1 , &num2 ) needs foo2 in C++ but this will not work in C.

Narendra
  • 3,069
  • 7
  • 30
  • 51
0

In C, there is no pass by reference. Instead you can pass the addresses to pointers, which essentially allows one to change the value of the variable passed.

The second function is in C++.

The two functions have a different signature, although they allow one to perform the same task.

sbetageri
  • 73
  • 1
  • 7