-2

In C (not C++)

what is the difference between:

function(int &a)
{
    a = a + 2;
}

and:

function(int *a)
{
    *a = *a + 2; 
}

For what I understand they are the same no?

If there are differences can you explain them with examples?

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
Miguel M
  • 302
  • 3
  • 16
  • 3
    `int &a` is not standard C code. It is C++. Are you learning C or C++? If you are learning C, the answer is not to use `int &a`; it is not valid. If you are learning C++, somebody may write an answer discussing differences between references and pointers. Pick one language, remove the tag for the other, and edit the question and title to clarify which language you are asking about. – Eric Postpischil Jul 06 '21 at 15:07
  • 1
    The second form uses pointers. The first form uses references, which are a C++ (not C) feature. One way to think about references is that they are a restricted form of pointer. – Steve Summit Jul 06 '21 at 15:09
  • 1
    This should not be closed as a duplicate until OP clarifies whether they are asking about C or C++. If they are asking about C, as they indicated, this is not a duplicate of that C++ question. – Eric Postpischil Jul 06 '21 at 15:10
  • 1
    The net effect is the same for both but the reference version is preferred because nobody can set a reference to null accidentally function(int *a) { a = NULL ; *a = *a + 2; // crash } – Edgen Jul 06 '21 at 15:11
  • 3
    @user3386109: It is not appropriate to remove the C tag when we do not know OP’s intent. OP may be learning C but have been confused by some C++ code they encountered, in which case this is a C question, should have a C tag, and should be answered that this is not valid C code. – Eric Postpischil Jul 06 '21 at 15:12
  • @EricPostpischil It is indeed about C – Miguel M Jul 06 '21 at 15:26
  • @MiguelM Which compiler are you using? – user3386109 Jul 06 '21 at 21:22
  • 1
    The net effect is the same for both but the pointer version is preferred because it is absolutely clear, throughout the function, that 'a' is accessed indirectly because of the asterisk. The use of C++ references, (and other such bodges, like var parameters in Pascal), cause more confusion than they are worth. – Martin James Jul 07 '21 at 08:28

1 Answers1

3

int &a is not code defined by the C standard and generally cannot be used in C. In C++, this declares a reference to an object, which is like a pointer but does not require * when using the object that is pointed to, cannot be changed once created, and cannot use a null pointer.

For C++, differences between pointers and references are discussed here. In C, you cannot normally use int &a. (It could be used in some hypothetical C implementation that supported it as extension, which is how C++ originated.)

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312