Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Condition checking in a for loop

Consider this code:

int main()
    {
        int i;
        int ints[3];
        ints[0] = 0;
        ints[1] = 1;
        ints[2] = 2;

        for(i = 0; (ints[i])<4 && i<3; i++)
        {
            printf("%d\n", ints[i]);
        }
    }

Is there a reason I shouldn't do this sort of conditioning in the loop? I mean, when i becomes 3, will it look for a non-existing value at ints[3]? And if yes, is it ok?, since the loop is going to terminate anyway? It compiles and runs fine, but I was just wondering if there is some sort of a hidden problem with this. Thanks.

like image 504
ivanibash Avatar asked Jul 22 '26 15:07

ivanibash


2 Answers

In the last iteration of this loop, the expression ints[i]<4 will access ints[3]. Since this access reads past the end of the array ints, the behavior is undefined in C. So yes, this is not good code. It may work most of the time, but the behavior is ultimately undefined.

like image 136
Matt Fichman Avatar answered Jul 25 '26 06:07

Matt Fichman


It will be better to do i < 3 && ints[i] < 4 because the second part of the statement is evaluated only if the first one is true. The way you have it, it will look for ints[3] that does not exist.

like image 37
unxnut Avatar answered Jul 25 '26 05:07

unxnut



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!