ahoura
ahoura

Reputation: 689

bool value isnt changing in objective C

I have the following code :

bool hasGoneDown = TRUE;

NSLog(@"%d", hasGoneDown);
    if(y > 700 && hasGoneDown == TRUE){
        [_game addToScore:600];

        hasGoneDown = FALSE;
    }

    if(y < 700){
        NSLog(@"we are IN : %d", hasGoneDown);
        hasGoneDown = TRUE;
    }

but for some reason the bool value does NOT change at all even when the conditions are set in the if statements, its always 1!

so what am I doing wrong?

MORE INFO

here is more info on what is being done there. this is a game, and technically there is a character jumping, and y var represents the y axis, so when the character jumps higher than 700, it should do certain stuff... the code above is being called constantly through out the game, but the value for the bool does NOT change AT ALL!

Upvotes: 2

Views: 931

Answers (2)

xuanweng
xuanweng

Reputation: 1939

bool hasGoneDown = TRUE;

NSLog(@"%d", hasGoneDown);
    if(y > 700 && hasGoneDown == TRUE){
        [_game addToScore:600];

        hasGoneDown = FALSE;
    }

    if(y < 700){
        NSLog(@"we are IN : %d", hasGoneDown);
        hasGoneDown = TRUE;
    }

If the whole code is in a function, it would always be true as you initialized it to be true whenever the function is being run.. I hope bool hasGoneDown = True is declared somewhere else as a global variable.. And your coditions.. I believe a more "tidy" version of your code is as follows:

if(y >= 700 && hasGoneDown == TRUE)
{
    [_game addToScore:600];

     hasGoneDown = FALSE;
}

else{
      NSLog(@"we are IN : %d", hasGoneDown);
      hasGoneDown = TRUE;
    }

Upvotes: 2

Carter
Carter

Reputation: 4758

First off, do not use "TRUE" and "FALSE". Use "YES" and "NO". Secondly you may have a problem with your logic. It's possible you may want to use a single "if/else" statement rather than two "if" statements. You'll have to evaluate that for yourself.

if(y > 700 && hasGoneDown == YES){
    [_game addToScore:600];

    hasGoneDown = NO;
}

if (y < 700){
    NSLog(@"we are IN : %d", hasGoneDown);
    hasGoneDown = NO;
}

Upvotes: 0

Related Questions