1

Possible Duplicate:
Passing pointer argument by reference under C?

Are reference variables a C++ concept? Are they available in C? If available in C, why is my code giving a compilation error?

#include <stdio.h>
#include <stdlib.h>

int main()
{
  int a = 10;
  int b = 20;
  int &c = a;
  int &d = b;
  return 0;
}

Output:

bash-3.2$ gcc test.c
test.c: In function `main':
test.c:12: error: parse error before '&' token

Why?

Community
  • 1
  • 1
aks
  • 4,695
  • 8
  • 36
  • 37

7 Answers7

11

C does not have references as a type. The '&' in C is used to get the address of a variable only. It cannot be used the way you are trying to use it in C.

Matt Davis
  • 45,297
  • 16
  • 93
  • 124
6
  1. It's a concept available on C++ (but not exclusively)
  2. No, it is not available in standard C.
  3. See 1 and 2. See *1 and *2.
Bruno Reis
  • 37,201
  • 11
  • 119
  • 156
6

You can't use this to declare variables:

int &c = a;

The operator & is used to get the memory address of a variable. So, you could write for example:

int a = 10;
int *c;
c = &a;
Alex Ntousias
  • 8,962
  • 8
  • 39
  • 47
4

Pass by reference isn't available in C, use simple pointers instead.

Lazarus
  • 41,906
  • 4
  • 43
  • 54
2

References are a C++ concept only. In C you are restricted to using only pointers.

Joe M
  • 251
  • 1
  • 6
2

It's been awhile but it looks like you are trying to assign the address of c to the value of a.

Correction: value of a to the address of c. (Thanks Chinmay Kanchi for pointing that out.)

Ken Henderson
  • 2,828
  • 1
  • 18
  • 16
1

No, reference is C++ only.

Camford
  • 770
  • 3
  • 5