tapio / rlutil

C and C++ utilities for cross-platform console roguelike game creation.
http://tapio.github.com/rlutil/
229 stars 42 forks source link

[C] Use define instead of constants #13

Closed Zorgatone closed 8 years ago

Zorgatone commented 8 years ago
const int KEY_ESCAPE  = 0;
const int KEY_ENTER   = 1;
const int KEY_SPACE   = 32;
// [...]

It should be:

#define KEY_ESCAPE   0;
#define KEY_ENTER    1;
#define KEY_SPACE   32;
// [...]

That's because if I try to use the value in a switch case, the C compiler cannot evaluate it on compile-time. I must use a lot of if/else-if/............/else and that sucks.

// [...]
int key;
bool playing = true;

while(playing) {
    key = getkey();

    switch(key) {
    case KEY_ESCAPE:
        playing = false;
        break;
    }
}
// [...]

Here is the GCC error:

19:03:54 **** Incremental Build of configuration Default for project crook ****
make all 
gcc -std=c11 src/crook.c -o bin/crook
src/crook.c: In function 'main':
src/crook.c:40:3: error: case label does not reduce to an integer constant
   case KEY_ESCAPE:
   ^
make: *** [all] Error 1
makefile:2: recipe for target 'all' failed

19:03:56 Build Finished (took 1s.115ms)
Zorgatone commented 8 years ago

Source >here<. I defined my own *_KEYs because I couldn't use the switch/case

tapio commented 8 years ago

Try the latest master where I changed it to enum, which works and is nicer here than either const int or #define.

Zorgatone commented 8 years ago

@tapio: wow that was super-fast! :heart: u