Today, I read from my predecessors Code , You can see a strange usage :##. I thought it was the new standard of c99. I checked the classic K & R and found that it was already a standard use of C language. It's only today that we know it's actually failed -_-!
# Is A preprocessing Operator Used in macro definition to connect actual parameters during macro parsing. A simple example is:
# Define CAT (a, B) a # B
Now, the effect of using CAT (T1, T2) in the Code is t1t2, which is connected as a whole.
# A major feature of # Is that for enumeration data, # You can obtain the enumerated "name" instead of the enumerated "value ". For example:
Enum
{
Enumname1= 2,
Enumname2= 3
} Et;
Et = Enumname2;
Then, the result of CAT (T, enumname2) is tenumname2.
This makes # very useful: For two associated giant enumeration types, using # can significantly reduce the conversion workload.
Imagine a situation where we need a very large enumeration to indicate the state. At the same time, each status corresponds to a Timer: state_timer. Each timer is named after the status name with timer _.
When entering each status, you need to start the timer in this status. To avoid writing a huge switch-case for conversion, our code can be as follows:
Enum State
{
Active,
Idle,
Suincluded,
Blocked,
//...
} ;
Enum State_timer
{
Timer_active,
Timer_idle,
Timer_susponded,
Timer_blocked,
//...
} ;
# Define Timer (state) timer _ # state
# Define Enter_state (State );\
{\
Start_timer (timer (State ));\
}
Void Start_timer ( Enum State_timer timer)
{
//...
}
In this way, through the processing of #, we can avoid a large switch-case or other conversion methods, and the code is much simpler.
Two days ago, I was hesitant about whether K & R of more than 20 yuan is worth buying. Now, it seems that the most important thing is to calm down and consolidate basic knowledge.