thebiglebowski11
thebiglebowski11

Reputation: 1461

ios int to float comparison always evaluates to true

I am trying to compare a CGFloat to an integer value. Based on this value, execute a conditional... pretty standard. However, this will always be true for some reason. I even print out the values and they are clearly less than 800.... I have tried a bunch of different combinations, the most recent is shown below, I thought maybe it was comparing the size of float and the size of the int based purely on its binary values, so I tried this risky little cast operation... Any ideas?

CGPoint textViewPoint = [scroller convertPoint:[textView center] toView:(UIView *)self.view];
        NSLog(@"the y coord is %f", textViewPoint.y);

    int size = (int)textViewPoint.y;
    NSLog(@"the yint %d", size);
    //move the main view, so that the keyboard does not hide it.
    //if  (self.scroller.frame.origin.y >= 0 && textViewPoint.y > 800.0);
    if(size > 800);
    {
        NSLog(@"moving up");

Upvotes: 0

Views: 576

Answers (1)

AliSoftware
AliSoftware

Reputation: 32681

The problem is the ; at the end of the if(size > 800); line, not the int vs. float comparison. Remove it and all should be OK.

This is because this semicolon is interpreted as the body of your if statement, and that's this NO-OP statement that is executed when the condition is true. Then, the rest of your code next to this if empty body is outside of the if body so is executed whatever the condition value. That's exactly as if you had written:

if(size > 800)
{
}
{
    NSLog(@"moving up");
}

Compiler Warning Tip

The compiler generally warns you about this mistake. Be sure that you have the "Empty Loop Bodies" warning activated in your project Build Settings (compiler flag -Wempty-body): this way the next time you do this mistake, you will have a warning about it and will know what is wrong and how to fix it.

Upvotes: 4

Related Questions