68

Does C have references? i.e. as in C++ :

void foo(int &i)
Kevin Reid
  • 37,492
  • 13
  • 80
  • 108
jacky jack
  • 701
  • 1
  • 5
  • 3

2 Answers2

84

No, it doesn't. It has pointers, but they're not quite the same thing.

In particular, all arguments in C are passed by value, rather than pass-by-reference being available as in C++. Of course, you can sort of simulate pass-by-reference via pointers:

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

...

int y = 0;
foo(&y); // Pass the pointer by value
// The value of y is now 10

For more details about the differences between pointers and references, see this SO question. (And please don't ask me, as I'm not a C or C++ programmer :)

Community
  • 1
  • 1
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
24

Conceptually, C has references, since pointers reference other objects.

Syntactically, C does not have references as C++ does.

sbi
  • 219,715
  • 46
  • 258
  • 445
  • 7
    Wrong, conceptually pointers and references are absolutely different. Pointer is an algebraic data type of null and a reference. Reference is just that, reference. The implication is type safety — it can be immediately seen if a function ever meant getting a null argument or not. – Hi-Angel Dec 22 '17 at 12:37
  • @sbi well, you could probably say that a null pointer references an object located at memory address `0`, though this implies that standard says nothing about null pointers — I do not know whether it's true. In any case there's a widely established practice to use a null value to mean specifically "the pointer does not reference anything", up to the point I doubt on even existence of a code that uses null to actually reference the null address, perhaps if exploits. IOW even if standard does not treat null pointers in any special way, *conceptually* a null pointer does not reference anything. – Hi-Angel Jan 01 '18 at 08:10
  • 2
    @Hi-Angel: So a pointer is a nullable reference. _Shrug._ That doesn't prevent pointers, _in general_, from being references. – sbi Jan 02 '18 at 01:33
  • @sbi okay, now, "nullable reference" is a thing distinct from just a "reference", because the later ensures not ever getting a null at compile time, whereas the former forces to make runtime checks *(or to just hope nobody passed a null)*. – Hi-Angel Jan 02 '18 at 16:32
  • 5
    @Hi-Angel: Did you just say __ references are not references? So a _long_ leg is not a leg? A _red_ carpet is not a carpet? _Snort._ You seem to be stuck with the syntactic definition of "reference" in C++, and fail to see the concept behind it. _HAND._ – sbi Jan 06 '18 at 00:22
  • 3
    @sbi I've used your term to avoid confusion. For some reason it didn't work out. My term for the matter is "algebraic data type of null and reference" *(or less in use but my personal preference "coproduct of null and reference")*, and you can't substitute null → long and reference → leg, and still get something sensible. – Hi-Angel Jan 06 '18 at 05:34