Joe said:
Flash Gordon said:
Joe said:
[snip]
#include <stdio.h>
int main ( void )
{long l = 420000;
long *lp = &l;
short *sp;
*sp = (short)*lp; /* ill-advised, but Let's Pretend */
This is very different. If you were trying to fix the code further up so
it would compile what you wanted was:
short *sp = (short*)*lp; /* ill-advised, but Let's Pretend */
How thick is my head ^ ?
We all make mistakes.
Am I not reading, with correction, the number that a smaller type thinks a
larger type was? My socks are well accounted for, but Scott Knuds not only
flew out of my hard drive, but is eating my lunch.
Your version of the code:
#include <stdio.h>
int main ( void )
{long l = 420000;
long *lp = &l;
short *sp;
*sp = (short)*lp; /* ill-advised, but Let's Pretend */
Writes through an uninitialised pointer which is undefined behaviour.
My partial correction:
#include <stdio.h>
int main ( void )
{long l = 420000;
long *lp = &l;
short *sp = (short)*lp; /* ill-advised, but Let's Pretend */
/* Use of *sp */
Tries to read a short from where a long was stored. On normal 2s
complement systems the part of the long that is read will depend on the
endianness of the system.
The standard also says:
| An object shall have its stored value accessed only by an lvalue
| expression that has one of the following types:74)
| — a type compatible with the effective type of the object,
| — a qualified version of a type compatible with the effective type of
| the object,
| — a type that is the signed or unsigned type corresponding to the
| effective type of the object,
| — a type that is the signed or unsigned type corresponding to a
| qualified version of the effective type of the object,
| — an aggregate or union type that includes one of the aforementioned
| types among its members (including, recursively, a member of a
| subaggregate or contained union), or
| — a character type.
I.e. don't do what the above code does.
It is also possibly in general (though unlikely in this specific case)
for short to have trap representations. If the part of the long that is
read as a short happens to be a trap representation for short (e.g. -0
on a 1s complement system where -0 is a trap) then you have again
invoked undefined behaviour.
The comments about ridiculous things happening are just to make the
point that the C standard does not care what happens, so anything your
compiler does, including something completely unexpected
He sounds like a dude, so you can be assured that I won't give him face, but
until otherwise motivated, I'll give him the benefit of the doubt. Thanks
for your reply. Joe
Your choice. Just don't expect any errors in its posts to be corrected.
--
Flash Gordon, living in interesting times.
Web site -
http://home.flash-gordon.me.uk/
comp.lang.c posting guidelines and intro:
http://clc-wiki.net/wiki/Intro_to_clc
Inviato da X-Privat.Org - Registrazione gratuita
http://www.x-privat.org/join.php