Why doesn’t this piece of code result in y == 0x100?
uint8_t x = 0xff;
unsigned y = ++((unsigned)x);
Check it out for yourself here: http://codepad.org/dmsmrtsg
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The code you posted is invalid form the point of view of C language. The result of any cast in C is an rvalue. It cannot be used as an argument of
++. Operator++requires an lvalue argument. I.e. expression++((unsigned) x)is non-compilable in standard C language.What you actually observe in this case is GCC’s “generalized lvalues” extension
http://gcc.gnu.org/onlinedocs/gcc-3.4.4/gcc/Lvalues.html
Per that extension (and contrary to the standard C), a cast applied to an lvalue produces an lvalue. When you attempt to write something into the resultant “generalized” lvalue, the value being written is converted twice: it is first converted to the type specified by the explicit cast, and then the intermediate result is converted again to the type of recipient object. The final result is placed into the recipient object.
For example, if with your
xyou doit will be actually interpreted by GCC as
and the final value of
xwill be0.And this is exactly what happens in your example. In GCC your
is equivalent to
which is in turn interpreted by GCC as
This is why you get
0inxas the result, and that is the0that then gets assigned to youry.This extension is referred to as deprecated by GCC docs.