I know working with uninitialized data is a sin, but I was doing this
experiment where I spawned an int onto the heap and checked it's
address, then deleted it, then redefined it as a new int on the heap.
This behaved as hoped: The address never changed--I believe this is
proof of good decision-making in where to allocate objects, but also a
warning not to use a deleted pointer.
What got weird is when I started toying around with how C++ (or at
least gcc's interpretation) handled uninitialized data:
Integer based types seemed to auto-initialize to some random number
(I'm guessing what was there before they were allocated to that spot).
Then, when I do x++ in the cout, it reads as zero, then the next time
I put it in a cout, another seemingly random number. Interestingly
enough, when I do a += to the x in the cout, it skips printing the
zero and goes straight to the random number--also, if I do the ++
outside the cout. I guess that has more to do with what int++ returns.
Chars were an exception: They initialized at zero (' ') and x++ gave a
predictable 1 ('☺'). What I found odd was that x-- remained at zero.
I'd always been told when a variable reaches it's maximum or minimum,
it "overflows" to the minimum or maximum. (I'll test this another day,
maybe.)
Floats are the ones that scare me. Here's some output of initializing
a float x, then printing it a bunch of times:
5.95081e-39
5.95095e-39
3.30589e-39
5.95081e-39
7.92254e+33
NaN x++
7.92252e+33
7.92252e+33
7.92252e+33
"NaN x++" is where I do x++ inside the cout.
Scary. Not only does it initialize randomly, but it keeps changing
until modified! Doing it with a double was similar, but x++ returned a
valid number and all values beyond that were one.
When I created an object (a struct called A with members a and b), I
found ints and floats alike were initialized to zero and only char*
and strings acted weirdly.
Can anyone supply me with rationality for any of this nonsense?
Particularly, I'm curious about why the float values are ever
changing. Could I base a random function on this?
--
[ See http://www.gotw.ca/resources/clcm.htm
for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]


|