CCS C Software and Maintenance Offers
FAQFAQ   FAQForum Help   FAQOfficial CCS Support   SearchSearch  RegisterRegister 

ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 

CCS does not monitor this forum on a regular basis.

Please do not post bug reports on this forum. Send them to support@ccsinfo.com

Some Casting question

 
Post new topic   Reply to topic    CCS Forum Index -> General CCS C Discussion
View previous topic :: View next topic  
Author Message
kmp84



Joined: 02 Feb 2010
Posts: 345

View user's profile Send private message

Some Casting question
PostPosted: Wed Jul 06, 2016 1:27 pm     Reply with quote

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: 19359

View user's profile Send private message

PostPosted: Wed Jul 06, 2016 2:22 pm     Reply with quote

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: 345

View user's profile Send private message

PostPosted: Wed Jul 06, 2016 3:14 pm     Reply with quote

Hello,
Yes "len" and "tmp" has to be initialized. It's my mistake. Main focus was typecasting.
Thanks Mr.Telmah!
Display posts from previous:   
Post new topic   Reply to topic    CCS Forum Index -> General CCS C Discussion All times are GMT - 6 Hours
Page 1 of 1

 
Jump to:  
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