2013/03/22

[c/c++筆記] typedef的用法小整理

  • typedef為storage class specifier
typedef不能跟其他storage class specifier(auto, register, extern, static)一起使用,例如:
typedef static int STATIC_INT; //error: multiple storage classes in declaration specifiers

但是下面用法是可以的:
typedef int MY_INT;
static MY_INT num = 3;

  • 一般data type的別名
typedef unsigned long size_;

size_t intSize = sizeof(int);
printf("%size of int = %ld\n", intSize);

  • 幫array別名
typedef int INT_ARR [10];

INT_ARR arr = {100};
printf("arr[0] = %d\n", arr[0]);

  • pointer type的別名

typedef int *INT_PTR;

int a = 3;
INT_PTR a_ptr = &a;
printf("a = %d\n", *a_ptr);
要注意跟const混用時可能會產生預期外的結果,例如:
typedef int *INT_PTR;

int arr[2] = {1, 2};
const INT_PTR arr_ptr = arr;
*arr_ptr = 0; //ok
arr_ptr++; //error: increament of read-only variable 'arr_ptr'
會這樣事因為const INT_PTR為int *const (constant pointer to integer)而非const int* (pointer to constant integer)
如果想要實現const int*,用下列即可
typedef const int* cINT_PTR
照本宣科也可以實現int *const
typedef int *const INT_PTRc

  • struct type的別名

typedef struct account
{
    char name[100];
    int money;
}ACCOUNT, *ACCOUNT_PTR;

ACCOUNT myAccount = {"ga", 1000};
ACCOUNT_PTR myAccountPtr = &myAccount;
printf("%s has $%d NTD\n", myAccountPtr->name, myAccountPtr->money);

  • function prototype的別名

#include <stdio.h>
int add(int, int);

typedef int MYFUNCTION(int, int);

int main()
{
    MYFUNCTION *myAdd = add;
    printf("3 + 2 = %d\n", (*myAdd)(3, 2));
    return 0;
}

int add(int a, int b)
{
    return a + b;
}

沒有留言:

張貼留言