Darcy Power
Darcy Power

Reputation: 313

"Case label value has already appeared in this switch" when no duplicate cases can be found

I am working on programming the game 2048 in C++ as an exercise to get familiar with the language. Originally, the code wasn't throwing any errors but I was getting some logic errors in the final product so I thought that the problem could be that I was using the logic gates incorrectly. I looked it up and apparently the correct syntax for or was || when I was only using |, after I changed all of them to || my switch statement started saying that there were duplicate cases when it doesnt seem like there are any. what could this be caused by?

void slide(char direction){
    int i;
    int j;
    switch (direction){
        case 'W' || 'w':
            for (j = 0; j < boardSize; j++){
                int firstZero = -1;
                for (i = 0; i < boardSize; i++){
                    if (board[i][j] == 0 && firstZero < 0){
                        firstZero = i;
                    }
                    if (board[i][j] > 0 && firstZero >= 0){
                        int temp = board[i][j];
                        board[i][j] = board[firstZero][j];
                        board[firstZero][j] = temp;
                        if (i != boardSize-1){
                            i = 0;
                            firstZero = -1;
                        }
                    }
                }
            }
        break;
        case 'A' || 'a':
        break;
        case 'S' || 's':
        break;
        case 'D' || 'd':
        break;
    }
}

Upvotes: 1

Views: 1036

Answers (1)

rawrex
rawrex

Reputation: 4064

You should look toward this approach:

case 'A': // If it is A, fall through 
case 'a': // If it is a, pick this case
    // Do something
    break;
// Other cases...

This way, the choice will fall through.

On why your form of the condition does not work:

Condition - any expression of integral or enumeration type, or of a class type contextually implicitly convertible to an integral or enumeration type, or a declaration of a single non-array variable of such type with a brace-or-equals initializer. - cppreference.com

A condition should evaluate to the value that is equal to the value of one of the constant_expressions on which it is tested on. This leads to the situation where the || is not evaluated as you expect; all the clauses evaluated to 1 (since both A and a aren't zero), hence the multiple cases are the same.

Bottom line: case label must be an integral constant expression.

Upvotes: 5

Related Questions