-4

I'm trying to return reference to variable in c code, however this code:

int& f()
{
  static int l = 10;
  return l;
}

doesn't compile via gcc:

main.c:5:4: error: expected identifier or ‘(’ before ‘&’ token
int& f()

But compiles well with g++. How can I achieve this in c?

too honest for this site
  • 12,050
  • 4
  • 30
  • 52
Zhani Baramidze
  • 1,407
  • 1
  • 13
  • 32

2 Answers2

0

C doesn't know what a reference is, so it gives up parsing at that point.

If you're compiling this "C" code in C++ mode then it will work.

tadman
  • 208,517
  • 23
  • 234
  • 262
0

C doesn't support references. To perform something similar, you need to return a pointer:

int *f()
{
  static int l = 10;
  return &l;
}
dbush
  • 205,898
  • 23
  • 218
  • 273