|
|
View previous topic :: View next topic |
Author |
Message |
GlenED7
Joined: 18 Oct 2018 Posts: 4
|
Casting Differences between Compiler versions |
Posted: Fri Oct 26, 2018 12:25 pm |
|
|
I ran across something recently and I am curious to get the forum's feedback on it. I observed a difference in one of my projects when upgrading from compiler version 5.059 to 5.081. Specifically it dealt with casting a 16-bit signed variable to a 32-bit unsigned variable. In each of the compiler versions I received different results. I could not find any reference to this behavior when searching the compiler's release notes.
I also cross checked this behavior in VS 2015 and it is consistent with the newer version of the compiler. But I do not know what the C standard on it is, nor could I find an example of this particular case.
Essentially when I run the example code below on the two different compiler versions I get the follow results.
Code: | unsigned int32 u32Test;
signed int16 i16Test = 0x8000;
u32Test = (unsigned int32)i16Test;
printf("Compiler Version: %s\r\n", getenv("VERSION_STRING"));
printf("Compiled For: %s\r\n", getenv("DEVICE"));
printf("Signed 16 (0x8000) to Unsigned 32: 0x%08lX\r\n", u32Test); |
Result 1:
Compiler Version: 5.081
Compiled For: PIC18F87J50
Signed 16 (0x8000) to Unsigned 32: 0xFFFF8000
Result 2:
Compiler Version: 5.059
Compiled For: PIC18F87J50
Signed 16 (0x8000) to Unsigned 32: 0x00008000
I feel as though when casting to an UNSIGNED type no sign extending should be occurring. I would expect a bit for bit promotion. But apparently I am wrong. Did CCS get this right? Am I crazy to expect a non-signed extended result when casting to an unsigned variable? |
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19195
|
|
Posted: Fri Oct 26, 2018 1:11 pm |
|
|
It's actually specified in the original K&R, as giving 'indeterminate results'.
On chips that have error indications, it would actually trigger a maths error, since the value cannot be represented by the target type.
Technically the newer conversion is actually 'right', since the target has a higher rank than the source, so the conversion should first be to the higher rank type (so to 32bit signed, and sign extended), then this will be converted to unsigned.
It's a classic though that C depends on you verifying that values are legitimate before working.... |
|
|
|
|
You cannot post new topics in this forum You cannot reply to topics in this forum You cannot edit your posts in this forum You cannot delete your posts in this forum You cannot vote in polls in this forum
|
Powered by phpBB © 2001, 2005 phpBB Group
|