Search code examples
carraysfor-loopcycle

Why can't I exit the for cycle when the condition becomes false?


I want the cycle to end when "0 00 00" is typed by the user. Here's the code:

main()
{
    int i, o[128], m[256], s[256];
    for(i = 0; o[i] != 0 && m[i] != 00 && s[i] != 00; i++)
        scanf("%d %d %d", &o[i], &m[i], &s[i]);
    printf("ok\n");
}

but the only way for it to end is by typing some characters.


Solution

  • As is currently written, i is incremented before the condition is checked, so every time you're just checking for indeterminate values, which exhibits undefined behavior.

    Use a do-while to ensure that the loop is executed at least once, while giving you more control:

    i = -1; // Note the -1 here!
    do{
        i++;
        scanf("%d %d %d", &o[i], &m[i], &s[i]);
    } while (o[i] != 0 && m[i] != 0 && s[i] != 0);