Re: This is undefined, but is it legal?
On Jul 27, 11:42 pm, Old Wolf <oldw...@inspire.net.nz> wrote:
On Jul 26, 9:08 am, James Kanze <james.ka...@gmail.com> wrote:
On Jul 25, 6:04 pm, jl_p...@hotmail.com wrote:
I've heard that if you've declared a variable (such as a
double or an int) and not initialize it, then the result of
printing out its value is undefined.
Anything you do with its *value* is undefined behavior. (You
can still take its address, or assign to it.) With the
exception of unsigned char and char.
And how are you writing them out? If you're just copying the
bits of a struct to disk, then you have no guarantee of being
able to read the data in the future.
Nobody's mentioned this explicitly yet :
AFAIK, it is not undefined to copy the bits
to disk and read them back, even if the variable
is uninitialized. (Of course the value is
still indeterminate after the garbage is read
back from disk).
That's a good point. I think it depends on how you do it, but
in most cases, it should be OK. All the C++ standard speaks
about directly is istream::read and ostream::write (and the
streambuf functions they used); for istream, ostream and
streambuf, the interface uses char*, so you're OK. For
wistream, wostream and wstreambuf? A wchar_t can have a
trapping representation. As for fread and fwrite, inherited
from C, they are required to do input and output "as if" using
fgetc and fputc, which means byte access as well (even if they
take a void*), and thus defined behavior.
For anything else, it depends on the implementation, but in
practice, it's hard to imagine a system level read or write
doing anything but byte accesses.
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34