简体   繁体   中英

When condition inside if statement is fractional

void main(void)
{
    int i;
    for(i=1;i<=5;i++)
    {
        if(i/5)
            continue;
        printf("%d",i);
    }
}

My simple query is,if the condition inside "if" is evaluated to a fraction,is it treated as 0?As here the output is 1234,so when condition is 1/5,2/5,3/5,4/5 it is prinnting values of i,when 5/5=1 it is executing continue statement.

i/5 will be treated as integer division (when i is int of course), no matter where it appears in ( if or whatever). So / between two integers will actually give you the quotient.

i / 5 will give 0 when i ∈ {0, 1, 2, 3, 4} and 1 when i = 5 .

The if statement executes the conditional statement (in this case the continue statement ) when its conditional expression is true . An integer value is casted to boolean as follows: zero becomes false , any other value becomes true . Since the expression does not evaluate to a non-zero value until i==5 , the conditional statement is not executed until then.

Whenever you have

if ( expr )

and the expr isn't obviously something that's true/false, you can always think of it like this:

if( (expr) != 0)

So if the expr evaluates to something fractional, well, as long as the fraction is not equal to 0, the condition will evaluate as true.

However, in your example, since i is an integer, i/5 will do integer division which will never give a fraction. And if i is less than 5, i/5 will be 0, which will end up making the conditional false.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM