Home > Net >  Alternative for if-break in c?
Alternative for if-break in c?

Time:12-03

Hello I am still a beginner when it comes to programming and I have been working on a checkers game. However, we cannot use 'break' to our program unless if its switch-case. How can I revise my work? I already tried to loop it using while.

int validateMove(int x1 , int y1)
{
    int a , b;
    printf( "Available coordinates to send the piece are: \n" ) ;


    a=1, b=1;

    while(board[x1-a][y1 b] == ' ')
    {
        if((x1-a)==-1 || (y1 b)==8) 
            break;
        printf("%d%d , ", x1-a , y1 b);
        a  ;
        b  ;
    }

    a=1 , b=1;

    while(board[x1 a][y1-b] == ' ')
    {
        if((x1 a)==8 || (y1-b)==-1) 
            break;
        printf("%d%d , ", x1 a, y1-b);
        a  ;
        b  ;
    }

    a=1 , b=1;

    while(board[x1 a][y1 b] == ' ')
    {
        if((x1 a)==8 || (y1 b)==8) 
            break;
        printf("%d%d , ",x1 a, y1 b);
        a  ;
        b  ;
    }

    a=1;
    b=1;

    while(board[x1-a][y1-b] == ' ')
    {
        if((x1-a)==-1 || (y1-b)==-1) 
            break;
        printf("%d%d , ", x1-a, y1-b);
        a  ;
        b  ;
    }

}

CodePudding user response:

You only provided us a snippet so this has not been tested. validateMove() doesn't return anything so I changed the return type from int to void. Consider introducing a constant for your magic value ' ', perhaps:

#define EMPTY ' '

I would extract a function instead of repeating yourself 4 times. return is then a suitable alternative to break:

void validateMoveHelper(int x1, int y1, int af, int bf, int v, int v2) {
    for(int a = 1, b = 1; board[x1   af * a][y1   bf * b] == ' '; a  , b  ) {
        if((x1   af * a) == v || (y1   bf * b) == v2)
            return;
        printf("%d%d , ", x1   af * a , y1   bf * b);
    }
}

void validateMove(int x1, int y1) {
    printf( "Available coordinates to send the piece are: \n" ) ;
    validateMoveHelper(x1, y1, -1, -1,  1,  8);
    validateMoveHelper(x1, y1,  8,  1, -1, -1);
    validateMoveHelper(x1, y1,  8,  1,  1,  8);
    validateMoveHelper(x1, y1, -1, -1, -1, -1);
}

Then I would extract those 4 rows of 4 values into a table t and run it in a loop. You want to document what the table contains, though, or maybe use an array of structs instead.

void validateMoveHelper(int x1, int y1, int t[4]) {
    for(int a = 1, b = 1; board[x1   t[0] * a][y1   t[1] * b] == ' '; a  , b  ) {
        if((x1   t[0] * a) == t[2] || (y1   t[1] * b) == t[3])
            return;
        printf("%d%d , ", x1   t[0] * a , y1   t[1] * b);
    }
}

void validateMove(int x1, int y1) {
    printf( "Available coordinates to send the piece are: \n" ) ;
    int t[][4] = {
        {-1, -1,  1,  8},
        { 8,  1, -1, -1},
        { 8,  1,  1,  8},
        {-1, -1, -1, -1}
    };
    for(int i = 0; i < sizeof t / sizeof *t; i  )
        validateMoveHelper(x1, y1, t[i]);
}
  •  Tags:  
  • c
  • Related