C FAQ question 16.7: http://c-faq.com/strangeprob/ptralign.html
I have a question regarding the line:
s.i32 |= (unsigned)(*p++ << 8);
I understand how this line of code works, but I don’t understand why it is not just written like this:
s.i32 |= (long) *p++ << 8;
or
s.i32 |= (unsigned)*p++ << 8;
Why is that?
=============================
struct mystruct {
char c;
long int i32;
int i16;
} s;
char buf[7];
unsigned char *p;
fread(buf, 7, 1, fp);
p = buf;
s.c = *p++;
s.i32 = (long)*p++ << 24;
s.i32 |= (long)*p++ << 16;
s.i32 |= (unsigned)(*p++ << 8);
s.i32 |= *p++;
s.i16 = *p++ << 8;
s.i16 |= *p++;
=============
Update:
It’s still not clear to me why casting should be performed after the shift operation for the line in question. Maybe, as a few words said: "This is an example, not the only opportunity."
If something is wrong with the two alternatives I proposed, add your answer. At the moment, I am choosing littleadv comment as the answer, although the order of priority for casting and <actually it didn’t bother me.
P.S. FAQ, .