arocon
arocon

Reputation: 77

What is the meaning of the following code?

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?

Upvotes: 1

Views: 272

Answers (3)

Hans Passant
Hans Passant

Reputation: 941665

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.

Upvotes: 2

Ming-Tang
Ming-Tang

Reputation: 17651

#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

Upvotes: 4

Robert S Ciaccio
Robert S Ciaccio

Reputation: 2715

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.

Upvotes: 4

Related Questions