automatic casting (or not?) in c
I'm trying to learn C from a Ruby/PHP/Java background, and I've found that you almost always explicitly cast things (at least in tutorials). Like, I always see things like
double x, y;
x = 1.0;
/*...*/
y = x*5.0;
However, it seems that on my Mac's version of GCC, automatic casting works.
Is leaving the .0 on things just a matter o开发者_运维百科f style, or do some C compilers not autocast?
A constant has the type it is being assigned to:
int i = 1;
double x = 2; // 2.0
explicit cast:
i = (int)x;
x = (double)i;
implicit cast:
i = x;
x = i;
type promotion:
x = i / 2.0; // i is promoted to double before being multiplied
x = (double)i / 2.0; // so evaluates as this
vs
x = i / 2; // i is not promoted because 2 is an int
x = (double)( i / 2 ); // so evaluates as this
When an implicit cast is unsafe (may cause loss of bits or precision), your compiler should warn you unless you have set too low a warning level. Alarmingly perhaps, in VC++ this means warning level 4 when the default is 3.
An explicit cast will suppress such warnings, it is a way of telling the compiler you are doing it intentionally. If you liberally apply casts without thinking you prevent the compiler from warning you when the potential loss of data or precision is not intentional.
If you have to cast, you should consider whether your data has the appropriate type to begin with. Sometimes you have no choice, or it is a convenient way of adapting to third-party code. In such cases an explanatory comment may be in order to make it clear that you really did think about it and not just habitually applying a cast.
Autocasting only works when you add precision (or at least don't lose any), e.g. int -> float, int -> char, char -> int.
Going the other way requires casting, since it is up to the programmer to decide how to lose precision. Typically this is done by flooring, but specific applications may call for randomly flooring and ceiling.
Leaving .0 is not a matter of style. It can be important; try displaying 3/5 and 3.0/5.0. They are very different.
精彩评论