0

This is a specific problem, but I can't seem to figure out what is wrong.

else if (X == 2)
        //move left
    {
        if (Level[X-1][Y] == 0);
        {

            cout << Level[X-1][Y] << "\n";
            cout << "\n MOVING LEFT from RIGHT\n";  //PROBLEM IS HERE

            Level[X][Y] = 1; // block it
            X = X - 1;
            moved = 1;
        }
    }

What I am doing is I am checking if Level[X-1][Y] is 1, indicating a column, so I can not move my player there. However for some reason, despite it being 1 and not 0 (as indicated by the output), the IF statement is still accessed. Any help will be appreciated.

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
msmf14
  • 1,449
  • 4
  • 13
  • 19
  • 4
    I think compilers can warn about this ([*and I was right*](http://coliru.stacked-crooked.com/a/b27d75968d98eb0b)). – chris Oct 22 '13 at 00:51
  • I'm not sure I understand. Why would it enter if the statement is false? My G++ compiler isnt giving any warnings either. – msmf14 Oct 22 '13 at 00:55
  • 1
    First, look at the warning message in the link. It's pretty clear. Secondly, add the warning options shown in the link's command line and I'm sure you will. – chris Oct 22 '13 at 01:00

3 Answers3

10

Your problem is here:

if (Level[X-1][Y] == 0);
                       ^

the ; ends the if statement. What follows the if statement is just a compound statement like this:

{
  //Code
}

and are completely valid on their own and have many uses, one use of which is creating a block scope.

For completeness sake if we go to the draft C++ standard section 6.2 Expression Statements we see that the ; just terminates a null statement. The grammar is as follows:

expression-statement:
  expressionopt ;
                ^                        

and it also says:

[...]An expression statement with the expression missing is called a null statement.[...]

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
6

Semi-colon!!!

   if (Level[X-1][Y] == 0);
paddy
  • 60,864
  • 6
  • 61
  • 103
  • 3
    Can you explain to the OP what the semicolon means? – pburka Oct 22 '13 at 00:58
  • wooopsies. Thanks a lot, silly question on my part, spent hours on this!! – msmf14 Oct 22 '13 at 00:58
  • @msmf14 - you're not the first to get hung up on something like this. Eventually, checking for that accidental semi-colon becomes automatic. Until then it can be very frustrating. – Pete Becker Oct 22 '13 at 11:57
4
if (Level[X-1][Y] == 0);
//                     ^

Get rid of this semicolon.

It would make the logic like this: if Level[X-1][Y] is zero, do nothing, then run the following code(the compound statement you thought was belong to the if). It's equivalent to:

if (Level[X-1][Y] == 0)
{
    ;
}
{
    cout << Level[X-1][Y] << "\n";
    cout << "\n MOVING LEFT from RIGHT\n";
    Level[X][Y] = 1;
    X = X - 1;
    moved = 1;
}
Yu Hao
  • 119,891
  • 44
  • 235
  • 294