0
for (size = 0; size < MAX; size++)
{
    // wait for hay until EOF
    printf("\nhaystack[%i] = ", size);
    int straw = GetInt();
    if (straw == INT_MAX)
    {
        break;
    }

    // add hay to stack
    haystack[size] = straw;
}

The above is a piece of code from find.c. If INT_MAX is the maximum limit of int, then shouldn't we consider the condition as:

straw >= INT_MAX

instead of

straw == INT_MAX

for the break statement?

Please corredt me if iam wrong.

1

In addition to being the maximum value that an int can represent, INT_MAX is the value returned by the CS50 library's GetInt function in case of error or EOF (see man get_int!)

Testing whether straw is greater than or equal to INT_MAX would still work because of the equal part, but the greater than part would be redundant and wouldn't make sense, because INT_MAX is the maximum value that GetInt can return, and it's actually not possible for an int value to be greater than INT_MAX in the IDE.

0

Suppose that INT_MAX = 10, we have two conditions if to consider:

if (straw == INT_MAX)
{
    break;
}

The condition if is true when straw = 10. In the second case:

if (straw >= INT_MAX)
{
    break;
}

the if condition becomes true for the first time when straw reaches the value of 10 ..., therefore they are equivalent.

0

int Straw can't hold a value above INT_MAX since it is an integer. If the user inputs a value higher than INT_MAX, the program will throw an error before that if statement. So it's unnecessary to put the >= in the comparison.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .