For example: when I round a float into an int, why should I use :
int i = (int) round(f);
Instead of :
int i = int round(f);
What is the difference between int and (int) in C?
an int
is the built-in type integer and (int)
is Type Casting .
In C float data values require more storage, So when you are storing a float value in an integer variable you are supposed to type cat it to truncate the fractional part before storing it.
ie int i = (int) round(f);
Did you actually try to compile the latter? I will not answer that until you report what the compiler says.
For the first version: That is a typecast (read about the semantics), telling the compiler to convert the value to the type in the parenthesis. Otherwise the compiler might (should) complain about assigning a more "powerful" type to a lesser.
Note that "powerful" here means the type can hold a larger range of values; not necessarily higher precision.
Edit: Yes, you will get "expected expression" for the latter. Because that is simply invalid. So, the simple and full answer is: because the second thing is not valid C and will not even compiler!
use int i
is a definition.
(int) round(f)
is casting the results of the round function to an integer, potentially truncating results of round
down to an integer
Well by convention, doing (int) on a float is typecasting the float to an int. I'm not quite sure why you'd do int _ = int _ , although it may work just as well. By convention though, many languages (there are exceptions) in which you typecast go by the syntax of
... = (_type_) yourdatavalue
Hope that helps!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.