Search code examples
cpointerspass-by-valuefunction-calls

C transmission as a pointer


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?


Solution

  • 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.