0

I am new to C. Can someone explain me whats the difference between these?

I usually use pointers like this:

int myFunction(int* something) {
  ...
}

int main() {
  int something;
  something = 0;

  myFunction(&something);
  ...
}

But I've found code which looks like this:

int myFunction(int& something) {
  ...
}

int main() {
  int something;
  something = 0;

  myFunction(something);
  ...
}

It seems like the exactly same thing for me. Is there any difference?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
Jax-p
  • 47
  • 1
  • 8

2 Answers2

3

As you mentioned, int myFunction(int& something) { is not valid C. It's a reference, which is used in C++.

C and C++ are different languages, despite the similarity in syntax.

In case, you want to modify the content of something, you need to pass a pointer to it to the called function and operate on the pointer. The pointer itself will be passed by value, but by derefrencing the pointer inside the called function, you can achieve the result of pass by reference.

So your first snippet is valid. You should use that in C.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
1
  • The former is a pointer, which is valid C.
  • The latter is a C++ reference, which is not valid C.

The most notable difference is "syntactic sugar". To access the contents of the pointer something, you'll have to type *something. When doing the same to the C++ reference something, you don't need the *.

A more subtle difference is that a pointer can be used for pointer arithmetic. For example, to implement the library function strlen, you could do something like this:

size_t strlen (const char* s) 
{
  const char* start = s;

  while(*s != '\0')
  {
    s++;
  }

  return (size_t)(s - start);
}

This wouldn't be possible if s was a reference. You'd have to use separate counters etc.

Note that a C++ reference is 100% functionally equivalent to a read-only pointer:

int* const something // C equivalent of a reference
Lundin
  • 195,001
  • 40
  • 254
  • 396