Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the inconsistent lines in C FAQ question 16.7?

Tags:

c

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 that line of code works, but I don't understand why it is not simply written as either:

s.i32 |= (long) *p++ << 8;

or:

s.i32 |= (unsigned)*p++ << 8; 

Why is it this way?

===========================

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); // line in question
s.i32 |= *p++;

s.i16 = *p++ << 8;
s.i16 |= *p++;

============

Update:

It's still not clear to me why the casting must be done after the shift operation for the line in question. Maybe as littleadv said, "It's an example, not the only possibility".

If there is anything wrong with the two alternatives I proposed, please add your answer. For now I am choosing littleadv's comment as the answer, although the order of precedence for cast and << was not really what confused me.

P.S. I could not direct the question to the author of the FAQ because he is no longer accepting any questions by email.

like image 783
Vince Lee Avatar asked Dec 19 '25 22:12

Vince Lee


1 Answers

Because casting is above << in the order of precedence, and you want the casting to be on the result of <<.

edit for clarifications

The reason the casting is done before shifting for long, and after shifting for unsigned is explained in a different question with the same code:

"This code assumes that getc reads 8-bit characters, and that the data is stored most significant byte first (``big endian''). The casts to (long) ensure that the 16- and 24-bit shifts operate on long values (see question 3.14), and the cast to (unsigned) guards against sign extension. (In general, it's safer to use all unsigned types when writing code like this, but see question 3.19.) ".

like image 60
littleadv Avatar answered Dec 22 '25 11:12

littleadv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!