Added a warning to the article (#22219)

* Added a warning to the article

Added a warning with an example, which can occur on older compilers.

* fix(guide): c for loop iterator misnomer

declaration not initialisation
This commit is contained in:
Krinjih
2018-11-19 02:56:43 +01:00
committed by Christopher McCormack
parent 27356882de
commit e5a531682f

View File

@ -99,3 +99,35 @@ for ( ; ; ) {
``` ```
An infinite loop occurs when the condition will never be met, due to some inherent characteristic of the loop. An infinite loop also called an endless loop, and it is a piece of coding that lacks a functional exit so that it repeats indefinitely. An infinite loop occurs when the condition will never be met, due to some inherent characteristic of the loop. An infinite loop also called an endless loop, and it is a piece of coding that lacks a functional exit so that it repeats indefinitely.
## Warning!
Some older versions of compilers don't support declaration inside the for loop:
```C
#include <stdio.h>
int main () {
int array[] = {1, 2, 3, 4, 5};
for (int i = 0; i < 5; i++) { // The int i = 0 will show you an error on older compiler versions
printf("Item on index %d is %d\n", i, array[i]);
}
}
```
You can solve this problem if you declare the variable before:
```C
#include <stdio.h>
int main () {
int array[] = {1, 2, 3, 4, 5};
int i; // You declare the variable before the for loop
for (i = 0; i < 5; i++) { // Now you won't have a problem
printf("Item on index %d is %d\n", i, array[i]);
}
}
```