If is executed even with the condition being false

Asked

Viewed 150 times

6

I have an excerpt from a function with the following code:

printf("caminho: %d\n", t);
printf("min: %d\n", min);
if( min >= t && t != -1);
{
    printf("oi\n");
    min = t;
    printf("min: %d\n",min);
}

and as a result I have:

way: 2

min: 1

hi

min: 2

The line printing "hi" is executed, even with the condition must be false.

Can someone tell me how this can happen?

  • 2

    Post the most complete code, at least the piece where the variables are declared. Better yet, post a minimal, compileable example that reproduces the problem.

1 answer

16


You have a semicolon in front of your condition if:

if( min >= t && t != -1);

Regardless of the outcome, nothing will happen.

Then you have a loose block:

{
    printf("oi\n");    
    min = t;
    printf("min: %d\n",min);
}

Who will be executed anyway.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.