View previous topic :: View next topic |
Author |
Message |
kmp84
Joined: 02 Feb 2010 Posts: 353
|
Some Casting question |
Posted: Wed Jul 06, 2016 1:27 pm |
|
|
Hello All,
Is there any problem on this code if not do some cast manipulation?
(Store data as int16 and return only LSB Byte):
Code: |
int8 TestFunc(int8 *data){
int8 i,len;
int16 tmp;
for(i=0;i<len;i++){
tmp+=data[i];
}
return tmp;// return only LSB Byte
} |
Thanks. |
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19515
|
|
Posted: Wed Jul 06, 2016 2:22 pm |
|
|
Obvious thing is that len is not initialised, and could contain anything. You might sum one byte, or 255.....
You are actually performing teo implicit casts. C does this all the time. If you pass any variable of the 'wrong' type, it'll attempt to cast it to the target type.
So the arithmetic when you add data[i], is 16bit, and this is converted to a 16bit value when used. Then tmp is cast to an 8bit value when passed to the return. |
|
|
kmp84
Joined: 02 Feb 2010 Posts: 353
|
|
Posted: Wed Jul 06, 2016 3:14 pm |
|
|
Hello,
Yes "len" and "tmp" has to be initialized. It's my mistake. Main focus was typecasting.
Thanks Mr.Telmah! |
|
|
|