2008-04-24

程式撰寫規範 [part 2]

Topic : 對編譯系統默認的data type轉換,也要有充分的認識。

Description : None

Example :

/*
* sample-63
*
* This sample shows the important of type conversions.
*
* Explicit type conversion can be forced ("coerced") in
* any expression, with a unary operator called a cast.
*
*      (type-name) expression
*
* Always remember use type conversion between different
* types variable assignment to avoid ambiguous.
*/

#include<stdio.h>

/* Using type cast to make sure the difference between types */
void typeCast(){

     unsigned int i;
     unsigned short int exam;

     i = 1234567;
     printf("sizeof(unsigned int) : %d\n", sizeof(unsigned int));
     printf("i : %#x\n", i);
     printf("i : %d\n", i);
     exam = (unsigned short int)i;
     printf("sizeof(unsigned short int) : %d\n", sizeof(unsigned short int));
     printf("exam : %#x\n", exam);
     printf("exam : %d\n", exam);
}

int main(int argc, char* argv[]){
     typeCast();
     return 0;
}

基本上這的sample是在要求當型別轉換(type casting)時,要把強制轉換寫上去,確保 programmer知道這是他要的。

沒有留言:

張貼留言