C/C++ Tips - typedef

1. Define new type name for basic data types

typedef double REAL;

// do NOT need to change source code
#ifndef _SIZE_T_DEFINED
#ifdef  _WIN64
typedef unsigned __int64    size_t;
#else
typedef _W64 unsigned int   size_t;
#endif
#define _SIZE_T_DEFINED
#endif

2. Define/simplify struct/union/enum names

struct tagPoint
{
    int x;
    int y; 
};

// In C codes, "struct" has to be added before.
struct tagPoint pnt;
// In C++, you can use tagPoint to define variables directly
tagPoint pnt;

typedef struct tagPoint
{
    int x;
    int y;
} Point;

// Then you can use "Point" directly in C codes.
Point pnt; 

3. Define a simple name for array

typedef int INT_ARRAY_10[10];
INT_ARRAY_10 arr;

4. Define a simple name for pointer

int *(*a[10])(int, char*);

// usually used to define callback function
// func 
typedef int *(*func)(int, char*);
// use new type func
func a[10];

5. Tips - In general cases, typedef is preferred than #define

// case 1
typedef char* pStr1;
#define pStr2 char*;

// s1 and s2 are both char* type
pStr1 s1, s2;
// s3 is char* type and s4 is char type
pStr2 s3, s4;

// case 2
typedef char* pStr;
char str[4] = "abc";

const char *p1 = str;
const pStr p2 = str;

p1++; // p1 is pointer, so p1++ works
p2++; // wrong !!! const type cannot do ++, it is as same as const type p2;

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值