First to summarize the usage of typedef
in C/C++. The usage can be categorized into three class:
- to indicate what a variable indicates
- to simplify a declaration, i.e.
struct
,class
- using typedef with pointers
- using typedef with typecasting
Here are some tips:
-
basically, typedef is define a more self-explained variable or constant. such as
typedef int meter_per_sec
, which means we can usemeter_per_sec
to declare a int variable, and so on. NOTE: it cannot be used interchangeably when usingunsign int
orunsign meter_per_sec
. -
typedef
can be used in C to eliminate the repitation ofstruct
orenum
when try to define a datatype in the main function such as:
in the main
function, we can use student_t to define a students instead of using the full identifier:
1struct _student Henry; //this is ture for C
in C++, we don’t need the struct
key word when declare a struct
type variable. When we define a _student
struct in C++, we just use _student Henry
.
- using typedef with pointer is quite neat:
is equivalent to the following:
This is mainly to eliminate the possibility that you miss a *
in one of the declaration and make it a Node type instead of Node* type.
Secondly, I found another interesting C trick that allow you write better switch statemement, in which you can use semantic case labels in stead of just numbers in int
.
1#include <iostream>
2
3enum Type {
4 INT,
5 FLOAT,
6 STRING,
7};
8
9void Print(void *pValue, Type eType) {
10 using namespace std;
11 switch (eType)
12 {
13 case INT:
14 cout << *static_cast<int*>(pValue) << endl;
15 break;
16 case FLOAT:
17 cout << *static_cast<float*>(pValue) << endl;
18 break;
19 case STRING:
20 cout << static_cast<char*>(pValue) << endl;
21 break;
22 }
23}
24
25int main() {
26 int nValue = 5;
27 float fValue = 7.5;
28 char *szValue = "Mollie";
29
30 Print(&nValue, INT);
31 Print(&fValue, FLOAT);
32 Print(szValue, STRING);
33 return 0;
34}