Skip to the content of the web site.

Lesson 301b: Declarations must occur outside the control sequence of a for loop

Previous lesson Next lesson


Up to this point, we have always declared controlling variables in the control sequence of a for loop:

	for ( int i{0}; i < N; ++i ) {
		// Do something with 'i'
	}

	// 'i' is already out of scope

In C, it is illegal to decare any variable in the control sequence for a for loop, and thus, all such variables must be declared prior to the for loop. Consequently, these variables stay in scope until we move out of the block containing the for loop:

	int i;

	for ( i = 0; i < N; ++i ) {
		// Do something with 'i'
	}

	// 'i' is still in scope

We have seen in a previous Lesson that initialization can only occur through assignment in C.


Previous lesson Next lesson