Question on References

Pages: 12
This question of mine is very basic and may even sound stupid. But hope i would get an answer :)


Lets consider the following function

1
2
3
4
5
char c;
char& getc()
{
  return c;
}


now this allows us to do

1
2
3
char c='b';
getc()='a';
c=getc();


reference is like another name for something. Now my question is, what exactly is happening?

1
2
3
4
5
char c;
char* getc()
{
  return &c;
}


Now with the above case we could replicate the same functionality.

1
2
3
char c;
*(getc()) = 20;
c=*(getc());


I can understand that in the case of pointers address is returned so I am changing the values that the addresses point to.. But I am not able to understand what exaclty is returned with references and therefore the whole picture

References are pointers, except the compiler puts the asterisk for you, and you can't have null references.

http://en.wikipedia.org/wiki/Syntactic_sugar
Last edited on
It is also un-fortunate the C++ committee uses the & syntax for different meanings. & can be termed as address-off operator, bitwise AND operator and in C++ a reference variable.

This inter-changeably meaning is what causes a lot of problem for C++ newbies and depending on usage it means different thing. In this aspect, Java fare better and is used as a teaching programming language in Uni (at least in my country).
Well, it's not like C++ was novel in that area. C uses the asterisk for declaring pointers, multiplication, dereferencing pointers, and multi-line comments; a comma can be an operator that "concatenates" expressions or a parameter separator; a period can be a decimal point or a member accessor; + and - take wildly different meanings depending on what characters are around them (what does a--->b+++c mean? [yes, that compiles, given the right declarations]).
Except for the pointer part and ->, all of those are present in Java, as well.

To be honest, I can't see how anyone would find it hard to understand that a character has different meanings depending on the context. Context-sensitive pattern matching is what humans do best!
Last edited on
Except for the pointer part and ->, all of those are present in Java, as well.


It is precisely the above that Java remove it from their language. It means a lot of ppl really get "stucked" or "stumped" between those pointer part and -> as you have said. It causes a lot of confusion.
No. The designers of Java had two main goals in mind: one marketing goal, which was to seduce C++ users who struggled to produce safe code, and one design goal that would facilitate that, which was to make it as hard for the programmer to shoot himself in the foot as possible.
Java didn't do away with pointers because it made the language hard to learn. The target audience already knew how to use pointers. It did away with them because, regardless of whether you know them or not, it's harder to write safe code that uses pointers. Syntax has nothing to do with it, it's about tracking information. Java was designed to move that task away from the programmer, who is bad at it, to the run time environment, which is good at it.
All in all, a great deal for C/++ programmers. At least where I live, we're still in high demand, yet we've become fairly rare, meaning we're very high-valued.
closed account (EzwRko23)

At least where I live, we're still in high demand, yet we've become fairly rare, meaning we're very high-valued.


I don't know where you live, but this is not true for the rest of the world.
From indeed.com:

"Java Programmer" Salary Estimate:
* $50,000+ (9283)
* $70,000+ (5711)
* $90,000+ (2597)
* $110,000+ (1163)
* $130,000+ (498)

"C++ Programmer" Salary Estimate:
* $50,000+ (4292)
* $70,000+ (2627)
* $90,000+ (1275)
* $110,000+ (646)
* $130,000+ (276)

So, Java programmers are just as high-valued as C++ programmers, except there are about twice as many job offers for them.

And you seem to miss the fact that Java **does have pointers**.
It doesn't have pointer arithmetic and manual memory management, which are features of low-level languages; but this doesn't have anything to do with the "->", "*" and "&" syntax.
The "*" syntax is not needed, because Java has just **one** semantic for argument passing: pass-reference-by-value, while C++ has three or more different semantics, which makes it much more complex.




I don't know where you live
Yes, I can see how clicking my name and reading my profile would be challenging.

but this is not true for the rest of the world
Should I assume "rest of the world" means "USA"? Because that's the region those results are for, I believe.

It doesn't have pointer arithmetic
Then it doesn't have pointers. It merely allows passing parameters by reference. If you can't perform operations on the reference, then it's not a pointer.
On one hand, easiness is a good thing for people who don't have the skills in programming (any language) to avoid shooting themselves in the foot with those dangerous features, however if you have a good to excellent amount of skill in programming at any level then the various other features of C++ can be really useful.

I'd like to thank xorebxebx for listing his statistics and source.

-Albatross

Speaking of shooting feet with programming languages:
http://www.fullduplex.org/humor/2006/10/how-to-shoot-yourself-in-the-foot-in-any-programming-language/
Last edited on
closed account (EzwRko23)

Should I assume "rest of the world" means "USA"?


No, but USA is the leader in the field of software production. They count more on this field, even though I could say **we** have better programmers (at least our teams win with them at TopCoder or ACM's competition year-by-year).


Then it doesn't have pointers. It merely allows passing parameters by reference. If you can't perform operations on the reference, then it's not a pointer.


Pointer points to some piece of memory, where data/objects live. References in Java do exactly that, so they are pointers. Anyway, pointer arithmetic is useless even in C++, you can do just everything the same with arrays alone. It was kept because ancient compilers were stupid enough to optimize array access properly, and needed help from the programmer.


It merely allows passing parameters by reference.

Java is pass-reference-by-value (or pass-pointer-by-value), not pass-by-reference.
Java references behave just as C poiters without arithmetic. C++ references behave much differently.
Last edited on
No, but USA is the leader in the field of software production.
So? That doesn't mean a statistic on job availability using the US alone as a sample can be validly extrapolated to the entire world.

Pointer points to some piece of memory, where data/objects live. References in Java do exactly that, so they are pointers.
If you can do something equivalent to this, regardless of syntax, I'll concede to you that they are pointers:
1
2
3
4
5
void f(T *p){
    int a;
    p=a;
    *p=0;
}


Anyway, pointer arithmetic is useless even in C++, you can do just everything the same with arrays alone.
Hurr durr. Please explain how you'd arrays of any kind without using pointer arithmetic.
Also note: x[y] <=> *(x+y) <=> *(y+x) <=> y[x]
<edit>
It was kept because ancient compilers were stupid enough to optimize array access properly, and needed help from the programmer.
That makes no sense no matter how I read it. "Compilers were stupid enough to optimize array access properly"? What?
</edit>

Java is pass-reference-by-value (or pass-pointer-by-value), not pass-by-reference.
Java references behave just as C poiters without arithmetic. C++ references behave much differently.
Oh, boy. Are you wearing your stupid hat today?
http://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_reference
Last edited on
helios wrote:
References are pointers, except the compiler puts the asterisk for you, and you can't have null references.

I used to have been told that pointers are generally slower because you have to add the asterisk-operator every time.. this seems to be kind of conflicting with that. Are they indeed just redefinitions for syntactic purposes or are they just so much alike that the difference is negligible ( but is there, other than syntax )?
Last edited on
The * operator doesn't make code slower. How much you type does not mean anything with regard to how fast code runs.

A lot of the time references and pointers have equal performance.
Disch wrote:
A lot of the time references and pointers have equal performance.

"A lot of the time", are there any concrete examples when either is slower or faster?
It depends on the compiler, really, and whether or not the dereference can be opitmized out.

You have better chances of the dereference getting optimized out if you use a reference or a pointer const, as the compiler will have a "guarantee" that the pointer will not change.

For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
int foo;

int* p = &foo;   // a pointer
int& r = foo;  // a reference
int* const pc = &foo;  // a pointer const

    //  <...>

// all the below lines accomplish the same thing:

foo = 5;  // the baseline "control", likely to be fastest

*p = 5;  // possibly slower, since p could point to anything, and may not point to foo here
  // (depending on what code is at <...> and how smart the compiler is)
  // so the dereference is less likely to get optimized out

r = 5; // probably just as a fast as control, as the compiler can easily optimize out the
   //  dereferencing and replace this line with the baseline control

*pc = 5;  // probably just as fast as control for the same reasons as the ref 



But really when you're asking performance questions, there never is an answer that's concrete and applicable to all situations. There's just too many factors.
Last edited on
closed account (EzwRko23)

"Compilers were stupid enough to optimize array access properly"

Ok, my bad, I edited that sentence and made it unclear. I meant, they were not clever enough to optimize array accesses properly - they simply converted them to pointers by using this well-known property:

x[y] <=> *(x+y) <=> *(y+x) <=> y[x]

1
2
3
4
5
void f(T *p){
    int a;
    p=a;
    *p=0;
}


Undefined behaviour because of 3 reasons:
1. read of uninitialized variable
2. casting an int to a pointer
3. write of a random memory...
This can do nothing, segfault, sing or kill all kittens in your neighborhood.


So? That doesn't mean a statistic on job availability using the US alone as a sample can be validly extrapolated to the entire world


Show the evidence it cannot be. Show your stats for Argentina :) Wherever I check, Java programmers don't earn significantly differently than C++ programmers, and there are about twice as many Java positions. I checked in Poland, US and UK.


http://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_reference


Yeah, read Wikipedia.... :D
Anyway, it doesn't claim anywhere Java is pass-by-reference. And from the definition written there - it certainly isn't. Java is pass-by-value, dude, and it always has been.
Last edited on
I meant, they were not clever enough to optimize array accesses properly - they simply converted them to pointers by using this well-known property
I assume you mean stack arrays.
1. If y in x[y] is a variable not even a modern compiler can optimize it. It has to fallback to pointer arithmetic.
2. No, stack arrays can't completely replace pointer arithmetic, anyway.

Undefined behaviour because of 3 reasons:
My bad. I was going to write something else and changed my mind as I was writing it. This is what I meant:
1
2
3
4
5
void f(int *p){
    int a;
    p=&a;
    *p=0;
}


Show the evidence it cannot be.
I don't need to. You're the one trying to prove statistically that in most of the world Java programmers make as much money as C++ programmers while at the same time there being more openings. Show me a statistic than can be reasonably applied to most of the world or shut up, but don't show me one of a small portion of it, perform some preposterous extrapolation on it, and then ask me to accept it as valid. Alternatively, provide a statistic that disproves my anecdotal evidence that where I live C++ programmers are more valuable.

Anyway, it doesn't claim anywhere Java is pass-by-reference.
What, you need concrete examples to be convinced? There's this thing called abstraction; you might want to try it out.

Yeah, read Wikipedia
I'm sure you'll find the exact same definition in any programming book. This isn't some super-advanced concept, man. I studied this definition in my second year of Laboratory (probably one of the few highlight of an otherwise mediocre year).

And from the definition written there - it certainly isn't. Java is pass-by-value, dude, and it always has been.
I can't believe I need to explain this.
Let's take a look at this:
1
2
3
void f(int *p){
    *p=0;
}
Yes, p is indeed being passed by value, but the data p points to, which is what's of real interest to this function is being passed by reference (pass by reference is a generic term that refers to passing an argument to a function without making a copy of that argument, regardless of the means used to pass that argument [pointers, C++ references, COW semantics, whatever]). The fact that the pointer is being copied isn't relevant. The call is still by reference.
closed account (EzwRko23)
Go back to the second year laboratory and study the definition once again, because it seems you studied it too little. Or read the cited Wikipedia excerpt once again, because you haven't understood. Or if you still have the problem, read this:

http://javadude.com/articles/passbyvalue.htm

Java is pass-by-value. For Objects this is sematically equivalent to pass-by-sharing.
Only low-cost Java code-monkeys say it is pass-by-reference.


Show me a statistic than can be reasonably applied to most of the world or shut up, but don't show me one of a small portion of it


USA + UK is not a small portion of it.
Last edited on

"Java Programmer" Salary Estimate:
* $50,000+ (9283)
* $70,000+ (5711)
* $90,000+ (2597)
* $110,000+ (1163)
* $130,000+ (498)

"C++ Programmer" Salary Estimate:
* $50,000+ (4292)
* $70,000+ (2627)
* $90,000+ (1275)
* $110,000+ (646)
* $130,000+ (276)


Actually the above statistics came as a surprise to me. My thinking is simple economics. Laws of Supply and Demand. In my country, there are definitely MORE Java programmers than C++ programmers. So if there is a vacancy which requires C++ skills, of course employers need to fork out more to get their desired C++ skill-set programmers.

Not to mention it is easier for a C++ programmer to transition to Java than the other way round. So the employer is effectively paying one salary and get TWO skill-sets in ONE. Isn't that a bargain ? It will be even sweet-er if the programmer can also do PLSQL, PHP, Perl, shell scripts, Visual Basic, C, etc etc etc.

Ok back to above statistics. The only reason I could think of is there are more Java projects being undertaken than C++ and that can explain the number of vacancies to fill and salary to attract else I cannot think of a logical reason.

Don't programmers do in-house legacy program maintenance any more ? Imagine a company has an existing C++ application in-house and will they employ Java programmers to maintain the C++ application ? Just like some banks still retain COBOL systems, they will employ Java or C++ programmers to maintain ?

Hmmm....


closed account (EzwRko23)

Actually the above statistics came as a surprise to me. My thinking is simple economics. Laws of Supply and Demand.


There is also a definitely higher demand for Java programmers than for C++ ones.
Most business software is written in Java and C#, not C++. C++ is almost non-existent in the web-app domain.


Not to mention it is easier for a C++ programmer to transition to Java than the other way round.
So the employer is effectively paying one salary and get TWO skill-sets in ONE.


No, it doesn't work like that. C++ is a much more complex language, but it is also used to write usually smaller and simpler systems than Java. The transition from C++ to Java can require a lot of time for learning all the libraries and concepts not found in C++ world. It is easy only if you keep solving with Java the same easy problems you were solving with C++.


Just like some banks still retain COBOL systems, they will employ Java or C++ programmers to maintain


I know of at least one bank in Poland that hires Java programmers to maintain the COBOL system, so you might be right. Anyway, you usually don't need top-notch programmers to maintain legacy systems. :)
Last edited on
Pages: 12