Two C Techniques: Typedef and Switch by "Symbol"

First to summarize the usage of typedef in C/C++. The usage can be categorized into three class:

  1. to indicate what a variable indicates
  2. to simplify a declaration, i.e. struct, class
  3. using typedef with pointers
  4. using typedef with typecasting

Here are some tips:

  1. basically, typedef is define a more self-explained variable or constant. such as typedef int meter_per_sec, which means we can use meter_per_sec to declare a int variable, and so on. NOTE: it cannot be used interchangeably when using unsign int or unsign meter_per_sec.

  2. typedef can be used in C to eliminate the repitation of struct or enum when try to define a datatype in the main function such as:

1typedef struct _student{
2   char name;
3   double score;
4} student_t;

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.

  1. using typedef with pointer is quite neat:
1typedef struct Node *Nodeptr
2...
3Nodeptr startptr, endptr, curptr, prevptr, errptr, refptr

is equivalent to the following:

1struct Node{
2...
3};
4
5struct Node *startptr, *endptr, *curptr, *prevptr, *errptr, *refptr;

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(&ampnValue, INT);
31  Print(&ampfValue, FLOAT);
32  Print(szValue, STRING);
33  return 0;
34}