On 24/02/2010 05:18, Grant Edwards wrote:
On 2010-02-24, Carl<[email protected]> wrote:Sorry, here is the code for the msp430: #include<io.h> int main(void) { short x = -32768; unsigned long y = -x; LPM0; } And same code as my previous posting for the PC: #include<stdio.h> int main() { short x = -32768; unsigned long y = -x; printf("sizeof short =%d, x=%d, y=%lu\n", sizeof(short), x, y); } As you can see there is no int type used.Yes, there is. The expression '-x' has a type of "int". On the MSP430, that's 16 bits and has a value of 0x8000. When you
It's important to note here that "0x8000" for a 16-bit int is -32768.
assign that to a long, it gets sign-extended to 0xffff8000. On the PC, '-x' is 0x00008000, and when assigned to a long, it's still 0x00008000. Don't take this the wrong way, but I think you need a good introductory book on C.
I don't think this is "introductory" stuff - even very experienced C programmers can get mixed up here. It took /you/ several posts to pin down the correct explanation, and you are well known for helping out with sticky C questions.
The best advice is to be very careful when dealing with corner cases at the limits of data type sizes, and with promotion between types. It is better to be explicit than implicit in such cases, and to use size-specific types ("int16" and "uint32" rather than "short" and "unsigned long") - that way you are clear on what you are doing.
mvh., David
