How can you tell whether a loop ended prematurely?

QuestionsCategory: C ProgrammingHow can you tell whether a loop ended prematurely?
AdminAdmin asked 4 weeks ago
Please follow and like us:
1 Answers
AdminAdmin answered 4 weeks ago

Generally, loops are dependent on one or more variables. Your program can check those variables outside the loop to ensure that the loop executed properly. For instance, consider the following example:

int x; char* cp[REQUESTED_BLOCKS];
/* Attempt (in vain, I must add...) to allocate 512 10KB blocks in memory. */
for (x=0; x< REQUESTED_BLOCKS; x++)
{ cp[x] = (char*) malloc(10000, 1); if (cp[x] == (char*) NULL) break; }
/* If x is less than REQUESTED_BLOCKS, the loop has ended prematurely. */
printf("Bummer! My loop ended prematurely!\n");

Notice that for the loop to execute successfully, it would have had to iterate through 512 times. Immediately following the loop, this condition is tested to see whether the loop ended prematurely. If the variable x is anything less than 512, some error has occurred.

Please follow and like us: