Code: Select all
/* some setup for example */
unsigned long x;
unsigned long *p = &x;
unsigned char *p2 = (unsigned char *)p;
*p2 = 0xff;
/* instead of *((unsigned char *)p) = 0xff; */
proxy
Code: Select all
/* some setup for example */
unsigned long x;
unsigned long *p = &x;
unsigned char *p2 = (unsigned char *)p;
*p2 = 0xff;
/* instead of *((unsigned char *)p) = 0xff; */
I still don't see "why" the casting code should be illegal... that is my point, what about it exactly was wrong.proxy wrote:first of all, r-value basically means "valid on right hand side of an assignment", so, logically, an l-value means "valid on the left hand side of an assignment"
as for why do some compilers allow it even if it isn't technically legal.
Well, just about every compiler out there isn't 100% standards compliant, not only that, but it is possible to have a compliant compiler which allows code with undefined behavior (as in just about anything could happen). Classic example of this is the XOR integer swap trick...commonly written like this:
a ^= b ^= a ^= b;
this will in principle swap the integer values of a and b...but this code is not legal! it violates sequence point rules (having to do with multiple assignments in one statement).. a legal way to write it is like this:
a ^= b;
b ^= a;
a ^= b;
just about no compiler will even warn on this example, but still, it is allowed to do anything, heck, hypothetically it is allowed to crash your computer (though it would likely work just fine).
Really it boils down to the fact that as far as compilers go, they are not a good way to determine if something is technically correct.
For more info on the l-value cast thing:
http://c-faq.com/ptrs/castincr.html
proxy
Code: Select all
unsigned char* fb = (unsigned char*) 0x000A0000;
*( fb + ( 200 + ( 6 * 320 ) ) ) = 0;
Code: Select all
unsigned char* fb = (unsigned char*) ( 0x000A0000 + ( 200 + ( 6 * 320 ) ) );
*fb = 0x4;