473,792 Members | 2,831 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

REFERENCES REVEALED


I understand variables/objects and pointer variables perfectly:

int X = 5;

int* pX = &X;

*pX = 4;

int** ppX = &pX:

**ppX = 3;
---

I know exactly how references "behave", but I want to know how they actually
work!

For instance, take the following function:

void Repot(unsigned int* pX)
{
*pX = 45U;
}
The caller will do the following:

int main(void)
{
unsigned int X = 17U;

Repot(&X);
}
Obviously one could rewrite the above code as:
void Repot(unsigned int& X)
{
X = 45U;
}
int main(void)
{
unsigned int X = 17;

Repot(X);
}
But what I want to know is what's actually going on under the hood. One
quick little side note here though before I continue: When I first learned
about references, I detested them, I thought they were extremely stupid. One
may argue that they're easier to use, just as one may argue that an
automatic transmission car is easier to driver, but long story short, I
prefer manual transmission and detest references. So anyway, I could find no
justification for the introduction of references into C++, other than to
make operator overloading for classes possible. I was pleasantly amused when
I heard a quote from Bjarne himself stating that the reason he introduced
references into C++ was to enable operator overloading for classes. Fair
enough, and although in my opinion it is heavily contrived, it works! Just
for clarification, here's what I hate so much about references: Before, when
calling a function, you could specify "X" to indicate the value stored in
the variable, and you could specify "&X" to indicate the memory address of
the variable. With references, this is no longer so. (Yes, I am aware that
one can determine from the function prototype whether or not it's a
reference... I don't like it).

So anyway, how does the compiler deal with references? Does it simply treat
them as short-hand? Would the compiler turn my preceeding code (written
using references) back into pointers? ie. would it simply stick in the "*"
and "&" where appropriate? If the answer to this is Yes, then I pressume
that both samples of code would compile identically and hence allocate the
same amount of memory. (That is, the use of a reference does not supress the
need to have another variable within which to store the address of another
variable, ie. a pointer variable). If this is so, everything is fine and
dandy and I understand references, regardless of whether I like them. If
this is NOT so, I am at a loss! Before, I used to just think of it as
follows: If a function has a reference as a parameter, then you can think of
it as the scope of the variable being extended to the function which has
been called. This concept worked fine for me until I came across functions
whose return type was a reference. This is where my brain started
stuttering. Take the function prototype:

unsigned int& TeachFarmAnimal s(void);

When you call the above function, what exactly are you getting back as a
return type?!! Are you simply receiving a pointer, and is the compiler just
sticking in the "*" and "&" for you where appropriate?
In summation:

Are references just pointers without the need to include "&" and "*", and is
the compiler just handling the "&" and "*" for you in the background?
-JKop
Jul 22 '05
33 2404
Mabden wrote:
int* k;
Parrot( &( *k = Monkey() ) );
[snip]
Can you guys figure it out and post the actual truth about how this works?
You mean the above?
That's undefined behaviour.
k is derefenced without having given a location to point to.
I
don't know enough to figure it out and you are getting less helpful as you
post snipettes. Somebody please summarize the argument and explain how
pointers (or const pointer) and references differ in the Real World (tm).


????
There have already been given some good answers.
Both are distinct concepts:
A pointer is a variable which holds a memory address.
A reference is another name to an existing object

Sometimes a compiler uses a pointer internally to implement
reference semantics. Sometimes not. The point with references
is, that for you as the programmer there is no legal way to
differentiate between the references and the thing it refers
to. For you, the programmer, they are the same thing.

int main()
{
int i;
int& j = i;
}

j and i are indistinguishab le. They are just 2 names for the
same memory location where an int is stored. How the compiler
does this magic is unimportant and completely transparent to you.

A pointer variable is a variable on its own: it has a value
and it has a location in memory where it resides.

--
Karl Heinz Buchegger
kb******@gascad .at
Jul 22 '05 #31
Karl Heinz Buchegger posted:
JKop wrote:

John Harrison posted:
> From the practical point of view there is the fact that a const
> reference can bind to a temporary, something a pointer cannot do.


int Monkey(void) { return 42; }

void Parrot(int* pBeak)
{

std:: cout << *pBeak;

}

int main(void)
{

int* k;
Parrot( &( *k = Monkey() ) );
system("PAUSE") ;

}

I love it!

If anyone could post something from the Standard regarding the
lifetime of temporaries, I'd appreciate it. As far as I know, the
above is valid, ie. DEFINED BEHAVIOUR!


Take more care!
The above is undefined behaviour. Where does k point to when you
dereference it. Just because it compiles and runs at your system
doesn't mean it is correct.

I'm not convinced that what I've done in the above is undefined behaviour.

Take the following function:
const unsigned long int* Tranquil(const unsigned long int& ostrich)
{
const unsigned long int* const pOstrich = &ostrich;

return pOstrich;
}
That's defined behaviour... Yes?
int main(void)
{
const unsigned long int* pFlamingo = Tranquil(55982U L);
}
And the above is also defined behaviour... Yes?
So what's wrong with my original example?!
-JKop
Jul 22 '05 #32
JKop wrote:
Karl Heinz Buchegger posted:

JKop wrote:
John Harrison posted:
From the practical point of view there is the fact that a const
reference can bind to a temporary, something a pointer cannot do.

int Monkey(void) { return 42; }

void Parrot(int* pBeak)
{

std:: cout << *pBeak;

}

int main(void)
{

int* k;
If you don't initialize k, where does k reside and what is the value at
that location?

For sake of argument, let's assume it resides at 0x80808080.

Ok, now, how about the value for k? Well, k is 4 bytes long and we know
it starts at 0x80808080 ... so, its going to be random, right? Lets just
say the 4 bytes starting from address 0x80808080 are 0xaabbccdd. Again,
what I'm referring to here is the random bit pattern that exists at the
address in memory where k resides.
Parrot( &( *k = Monkey() ) );


Now, assume this works as you think, where does the value '42' get written?

assuming k resides at memory address 0x80808080
and the value of k = 0xaabbccdd

then ----> the operating system jumps to address
0xaabbccdd and writes the value 0x0000002a.

Notice, the location where k resides hasn't changed ... and the actual
bit pattern at that location didn't change. Your code will change the
bits at the random address that k is holding or pointing to.

So, we agree that the value of k is random right? What if the bit
pattern at address 0x80808080 is 0x00000000 or NULL. We don't know? It
could be. There's no of any value.

So try this:

int* k = 0;

In this case, *k* is validly declared - and so, let us assume it still
resides at address 0x80808080. But this time, we assigned a value to the
4 bytes. The 4 bytes from 0x80808080 ~ 0x80808084 will be 0x00000000.

Now try:

*k = 5;

What do you get? Sure, it compiles fine. It won't run. Why not? Well, it
just so happens that NULL or 0x0 is an address that cannot be written to.

So, in your example, if the value of k at address 0x80808080 equals NULL
or 0x00000000, what will happen when you try to write the value 42 to *k.

Do you understand what happens when you dereference a pointer? The value
is not written to the location the pointer exists in memory - it is
written to the place the pointer _points-to_ in memory. In this example,
we are trying to write the value '42' to the address location 0x00000000
and that will break.

Take this example and extend it. Imagine a memory address too large.
Imagine a memory address already in use in the system. Remember, the
bits at k are going to be random ...

Your example as its written, isn't really about temporaries. Its about
dangling pointers.

This question actually goes back to when you didn't agree with Julie
that dangling pointers are _bad_. When one dereferences a dangling
pointer, its possible they may point to memory that the compiler is
happily using for other things. Writing, reading, etc. If you try to
access memory with a dangling pointer, you're not going to necessarily
break anything - but you can't depend on anything being there ... since
the operating system is tracking and using memory like a mad man.

And if you write to a dangling pointer - you might be overwriting
something the OS just put there. Or, you might be writing to a blank
area - or you might be writing to NULL (which would throw an exception).

Maybe _bad_ isn't the word, but the resulting behavior is unpredictable
if you tried to write or read from a dangling pointer -- and therefore,
it is undefined.

Hth,

-Luther

(If all this pointer talk is confusing, try reading K&R or some other C
text).
Jul 22 '05 #33
Luther Baker posted:
JKop wrote:
Karl Heinz Buchegger posted:

JKop wrote:

John Harrison posted:
>From the practical point of view there is the fact that a const
>referenc e can bind to a temporary, something a pointer cannot do.

int Monkey(void) { return 42; }

void Parrot(int* pBeak)
{

std:: cout << *pBeak;

}

int main(void)
{

int* k;


If you don't initialize k, where does k reside and what is the value at
that location?

Opps!!

Rookie mistake! I didn't look close enough at my code.

Believe me, I know exactly what my original code is doing:

int *pHello;

*pHello = 5;
I was just focusing too much on trying to get the address of the return
value from the function, and I was wasn't watching the road!

I know realize that you simply just can't get the address of the return
value from a function!
-JKop
Jul 22 '05 #34

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

22
2247
by: xmp333 | last post by:
Hi All, I am trying to hide my JavaScript source. The method I chose was to keep all the important source in a password protected folder, and then use a SRC="folder/script.js" to include it in my code. This way, the script will run, but the user will be unable to view the included code. Or so I think :). I have tried this method, and it seems to work. However, I would like
354
15928
by: Montrose... | last post by:
After working in c# for a year, the only conclusion I can come to is that I wish I knew c. All I need is Linux, the gnu c compiler and I can do anything. Web services are just open sockets hooked up to interfaces. The Gtk is more than enough gui.
2
32207
by: Michelle Collier-Moore | last post by:
Please could someone offer some advice regarding adding references to an Access database? I tried to open a project a few days ago sent to me by someone whose developer had left the company. I found that I had a reference problem and went to the usual Tools, References place to fix it. The References option was greyed out and as I have never seen this happen before, after trying various things, searching here for an answer etc. gave up!!
2
22293
by: S. van Beek | last post by:
Dear reader, For removing a reference in the VBA reference form I receive from Doug Steele the following code: ........... References.Remove refCurr
9
1336
by: Xah Lee | last post by:
in coding Python yesterday, i was quite stung by the fact that lists appened to another list goes by as some so-called "reference". e.g. t=range(5) n=range(3) n='m' t.append(n) n='h' t.append(n) print t
30
2490
by: jeremygetsmail | last post by:
I've got an adp (Metrix.adp) with a reference to another adp (InteractSQL.adp). InteractSQL sits on a server, and is refered to by all of the clients (Metrix), which sit on the client machines (There's also a SQL Server that sits on the server, but that's besides the point here.). Both adp files have references to ADOX. I've got to check Metrix has an older version of ADOX, and react appropriately. I've written code to do this, and it...
9
2474
by: igor.kulkin | last post by:
References is a relatively basic feature of C++ language. It might be a good thing to think of references as aliases to the variables. However it's good to think of references this way when you deal with references which are local variables. But references can also be function arguments (in fact they are more useful this way) in which case it has to have the in-memory representation.
76
4720
by: valentin tihomirov | last post by:
As explained in "Using pointers vs. references" http://groups.google.ee/group/borland.public.delphi.objectpascal/browse_thread/thread/683c30f161fc1e9c/ab294c7b02e8faca#ab294c7b02e8faca , the pointers are allowed to be null, while references must refer an existing variable of required type. The null is normally used for making optional parameters. But there is no way to pass null reference in C#. Something is missing.
29
35507
weaknessforcats
by: weaknessforcats | last post by:
Arrays Revealed Introduction Arrays are the built-in containers of C and C++. This article assumes the reader has some experiece with arrays and array syntax but is not clear on a )exactly how multi-dimensional arrays work, b) how to call a function with a multi-dimensional array, c) how to return a multi-dimensional array from a function, or d) how to read and write arrays from a disc file. Note to C++ programmers: You should be using...
0
9670
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9518
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10430
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10211
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10159
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9033
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7538
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
2
3719
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2917
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.