My Computer Forum Computer Science Forum

Go Back   My Computer Forum > Computer Science Forum > Programming

Programming Programming Languages, Interpreters, and Compilers - Assembly, Declarative, Machine, Object Oriented, Iterative


Reply
 
LinkBack Thread Tools Display Modes
January 24th, 2009, 12:26 AM   #1
 
Joined: Oct 2008
Posts: 16
Typecasting in C

I have the following code:

int hours_result;
float intermediate;
.
.
.
hours_result = (int)floorf(intermediate);

Is it 'safe' to rewrite the above as

hours_result = (int)intermediate; ?

Does the typecast behave in a reliable manner (that is, do I always get the integer part of the float) or is it best to use floorf() or some similar function to remove the numbers to the right of the decimal, and then cast to int?
greg1313 is offline  
 

My Computer Forum is free to register and we welcome everyone!

January 28th, 2009, 09:41 PM   #2
 
Joined: Dec 2007
Posts: 232
Re: Typecasting in C

It looks like if you really want all standard-compliant compilers to behave the same way, you need the floor:

C99 standard, section H.2.4, paragraph 2:
Quote:
In the above conversions from floating to integer, the use of (cast)x can be replaced with (cast)round(x), (cast)rint(x), (cast)nearbyint(x), (cast)trunc(x), (cast)ceil(x), or (cast)floor(x). In addition, Cís floating-point to integer conversion functions, lrint(), llrint(), lround(), and llround(), can be used.
So the standard seems to allow (int)4.1 to be evaluated to 5. On the other hand, I've never seen that behavior.
CRGreathouse is offline  
February 8th, 2009, 07:44 PM   #3
 
Joined: Oct 2008
Posts: 16
Re: Typecasting in C

Thanks. Sounds like using the floorf() is the way to go...
greg1313 is offline  
February 9th, 2009, 02:38 PM   #4
 
Joined: Dec 2007
Posts: 232
Re: Typecasting in C

Quote:
Originally Posted by greg1313
Thanks. Sounds like using the floorf() is the way to go...
I guess. Maybe define a casting macro so you can change it later?
CRGreathouse is offline  
February 20th, 2009, 03:09 PM   #5
 
Joined: Oct 2008
Posts: 16
Re: Typecasting in C

Quote:
Originally Posted by CRGreathouse
Quote:
Originally Posted by greg1313
... Maybe define a casting macro so you can change it later?
It's been a long time. How would I do this?
greg1313 is offline  
February 21st, 2009, 08:11 PM   #6
 
Joined: Dec 2007
Posts: 232
Re: Typecasting in C

I believe
Code:
#define toint(x)          ((int)floorf(x))
would do it. Then just call it with toint(foo).
CRGreathouse is offline  
February 22nd, 2009, 07:54 AM   #7
 
Joined: Oct 2008
Posts: 16
Re: Typecasting in C

Yes, I see. Thanks!
greg1313 is offline  
Reply

  My Computer Forum > Computer Science Forum > Programming

Tags
typecasting



Thread Tools
Display Modes






Copyright © 2018 My Computer Forum Forum. All rights reserved.