开发者

What is the meaning of the following code?

开发者 https://www.devze.com 2023-01-31 14:37 出处:网络
What is the meaning of following code : //Keyboard map #define LEFT_ARROW\'P\' #define RIGHT_ARROW\'Q\' #define UP_ARROW\'K\'

What is the meaning of following code :

//Keyboard map
#define LEFT_ARROW      'P'
#define RIGHT_ARROW     'Q'
#define UP_ARROW        'K'
#define DOWN_ARROW      'L'
#define CANCEL          'F'
#define HOME            'A'
#define BLANK           'B'
#define SIGN_TOGGLE     'G'
#define KB_DECIMAL      'R'
#define KB_ZERO         'S'
#define KB_ONE          'C'
#define KB_TWO          'D'
#define KB_THREE        'E'
#define KB_FOUR         'H'
#define KB_FIVE         'I'
#define KB_SIX        开发者_开发技巧  'J'
#define KB_SEVEN        'M'
#define KB_EIGHT        'N'
#define KB_NINE         'O'
#define ENTER           'T'

Could anybody explain how it works and why they defined in that way?


Those are just constants. It means that the preprocessor will go through the source code and replace any instance of the word following #define with the character on the right, before compiling the source code. So if there was a line like this in the code:

char myChar = LEFT_ARROW;

the preprocesor will change that code into:

char myChar = 'P';

before compiling.


#define TOKEN REPLACEMENT is a preprocessor directive, it replaces all occurrences of TOKEN into REPLACEMENT, syntactically.

The purpose of your code snippet is to assign names to keyboard bindings, that means, if you say if (key == KB_NINE), the compiler will see if (key == 'O').

The advantage of using preprocessors correctly is not only readability: it also increases maintainability, in case the constants change.

The key definitions seems to be nonsense: for example, KB_ONE is 'C', however, this problem can be solved in a few keystrokes by modifying the constant in one place.

See also: http://en.wikipedia.org/wiki/C_preprocessor#Macro_definition_and_expansion


These are the kind of keys you'd find on the right-hand side of a keyboard. There is no standard way in the C runtime to let a program recognize these keystrokes. So there have been all kinds of non-standard extensions to fix this problem.

One scheme is to let getch() return 0 when such an extended key is pressed, the next getch() call then returns a key code for that extended key. That key code could be the original keyboard scan code. Anything is possible, you'd have to know the original keyboard vendor and CRT supplier to have a clue. Clearly it is ancient, proprietary keyboard interfaces was an excellent vendor lock-in strategy back in the neolithic days of computing.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号