Page 1 of 1
alias/reference variable in C
Posted: Sat Aug 30, 2014 7:39 am
by dansmahajan
It may be a stupid question but I'm not able to find the answer- why there is no reference variable in C like C++??
I think answer might be some approved C standard but i'm not sure, so what do you think ??
Re: alias/reference variable in C
Posted: Sat Aug 30, 2014 7:52 am
by Icee
Because references are basically pointer sugar, and C was specifically designed to have explicit pointer operations and as little sugar as possible.
Re: alias/reference variable in C
Posted: Sat Aug 30, 2014 11:14 am
by dansmahajan
@Icee: Thank you very much.
Re: alias/reference variable in C
Posted: Sat Aug 30, 2014 9:35 pm
by Wajideu
You could probably get away with this though
Code: Select all
int *a = ({ static int _a = 0; &_a });
It's part of a gcc function expression extension, so it definitely won't work in most compilers (if at all)
Re: alias/reference variable in C
Posted: Sat Aug 30, 2014 10:47 pm
by dansmahajan
@DaemonR: Thank you.
But this will again involve pointers(which are apparent to programmers) and will have their own memory address whereas in C++ reference variables variable and its alias share the same memory address(Correct me if I'm wrong).
Re: alias/reference variable in C
Posted: Sat Aug 30, 2014 11:03 pm
by Wajideu
dansmahajan wrote:@DaemonR: Thank you.
But this will again involve pointers(which are apparent to programmers) and will have their own memory address whereas in C++ reference variables variable and its alias share the same memory address(Correct me if I'm wrong).
This in C++
Is roughly the same as this in C:
It's just syntactical sugar.
Re: alias/reference variable in C
Posted: Sun Aug 31, 2014 2:15 am
by Brendan
Hi,
DaemonR wrote:This in C++
Is roughly the same as this in C:
It's just syntactical sugar.
Yes; and this in C++:
Is roughly the same as this in C:
Except for the fact that in C the caller would do "foo(&bar);" (which makes it obvious that bar may be modified), and in C++ the caller does "foo(bar);" where it looks like the variable is passed by value and safe from modification when it's not.
This is what makes it "syntactical sugar poured into your gas tank".
Cheers,
Brendan
Re: alias/reference variable in C
Posted: Sun Aug 31, 2014 3:10 am
by bluemoon
Brendan wrote:Except for the fact that in C the caller would do "foo(&bar);" (which makes it obvious that bar may be modified), and in C++ the caller does "foo(bar);" where it looks like the variable is passed by value and safe from modification when it's not.
Agree, therefore I still pass by pointer when the value would be modified, although this means adding an extra a null check.
Pass by reference is still useful when it's const:
Code: Select all
int foo(const MyClass& c) {
return c.get_foo();
}