Johny Johny - 1 year ago 57
C Question

What does this shortened code mean in C (inside int_wall function)

This is the part of MAZE algorithm. The shortened part of this code which is in the function is not so clear. Is my suggestion correct?

#define UP 1
#define RIGHT 2
#define DOWN 4
#define LEFT 8
int wall_ahead(int m[MAZE_SIZE][MAZE_SIZE], int x, int y, int dir){
x = (dir == LEFT) ? --x :
(dir == RIGHT) ? ++x : x;
y = (dir == UP) ? --y :
(dir == DOWN) ? ++y : y;

return m[x][y];

My Suggestion is:

if(dir == LEFT){
x -= 1;
x += 1;
} else {
x = x;

Answer Source

You want to use a switch statement, like this:

switch (dir) {
case UP:
    --y; break;
case DOWN:
    ++y; break;
case LEFT:
    --x; break;
case RIGHT:
    ++x; break;

Doing the assignments like the original listing is plain wrong, these prefix operators already modify the value.

OTOH, it seems UP and DOWN would be mutually exclusive, but not to RIGHT and LEFT and the same applies the other way around, so this would be more correct:

x += !!(dir & DOWN) - !!(dir & UP);
y += !!(dir & RIGHT) - !!(dir & LEFT);

Also, not so important, but there are a couple of typos in the original listing... check out those... and you need to give it the dimensions of the array, otherwise the address calculation can't be done by the compiler.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download