What happens if a conditional isn't supplied to a For Loop?

61 Views Asked by At

Consider this snippet:

int numbers[9] = {5, 2, 78, 23, 8, 9, 3, 12, 97};
int arrLength = (sizeof(numbers) / sizeof(int));

for(int i = 0; arrLength; i++) {
    printf("%d\n", numbers[i]);
}

I'd given an array length as the second parameter to the loop, but gave it no conditional for when to stop. The out gave the 9 numbers inside my array and then continued. Here is an example of the program output. The program output easily over 100 digits in this manner. Can anyone explain what is at play?

enter image description here

1

There are 1 best solutions below

2
Sourav Ghosh On BEST ANSWER

In this case, the condition is supplied.

 for(int i = 0; arrLength; i++)

is the same as

for(int i = 0; arrLength != 0; i++)

In other words, the controlling expression (a.k.a. condition check) should evaluate to TRUE for continuing the execution of the loop body.

From C11, chapter 6.8.5, P4

An iteration statement causes a statement called the loop body to be executed repeatedly until the controlling expression compares equal to 0. [...]

and, footnote 158, for loop

[...]the controlling expression, expression-2, specifies an evaluation made before each iteration, such that execution of the loop continues until the expression compares equal to 0; [...]

In case the condition is not supplied, it's considered as a non-zero (always true value).

Chapter 6.8.5.3, Paragraph 2

Both clause-1 and expression-3 can be omitted. An omitted expression-2 is replaced by a nonzero constant.