Microchip Technology XC8 Standard Compiler (Workstation) SW006021-1 SW006021-1 ユーザーズマニュアル

製品コード
SW006021-1
ページ / 518
MPLAB
®
 XC8 C Compiler User’s Guide
DS52053B-page 46
 2012 Microchip Technology Inc.
3.4
WRITING SOURCE CODE
This section presents issues pertaining to the source code you write. It has been 
subdivided into sections listed below.
3.4.1
C Language Specifics
This section discusses source code issues that are directly relates to the C language 
itself but which are commonly asked.
3.4.1.1
WHEN SHOULD I CAST EXPRESSIONS?
Expressions can be explicitly case using the cast operator -- a type in round brackets, 
e.g., (int). In all cases, conversion of one type to another must be done with caution 
and only when absolutely necessary.
Consider the example:
unsigned long l;
unsigned int i;
i = l;
Here, a long type is being assigned to a int type, and the assignment will truncate 
the value in l. The compiler will automatically perform a type conversion from the type 
of the expression on the right of the assignment operator (long) to the type of the 
lvalue on the left of the operator (int).This is called an implicit type conversion. The 
compiler will typically produce a warning concerning the potential loss of data by the 
truncation.
A cast to type int is not required and should not be used in the above example if a 
long
 to int conversion was intended. The compiler knows the types of both operands 
and will perform the conversion accordingly. If you did use a cast, there is the potential 
for mistakes if the code is later changed. For example, if you had:
i = (int)l;
the code will work the in the same way; but, if in future, the type of i is changed to a 
long
, for example, then you must remember to adjust the cast, or remove it, otherwise 
the contents of l will continue to be truncated by the assignment, which may not be 
correct. Most importantly, the warning issued by the compiler will not be produced if the 
cast is in place.