error: 'for' loop initial declaration used outside C99 mode


If any variable is declared inside the for loop, it will throw c99 mode error.

#include <stdio.h>
#include <string.h>

void printArray(char arr[], int n)
{

    for(int i=0; i<n; i++) {
        printf("%c - ", arr[i]);
    }
    printf("\n");
}

int main()
{
    int n = 10;
    char arr[10] = "Shirley";

    printArray(arr, n);
    printf("Array before memset() arr %s and sizeof(arr) %d strlen(arr) %d\n", arr, sizeof(arr), strlen(arr));
    // Fill whole array with 0.
    memset(arr, '\0', sizeof(arr));
    printf("Array after memset()\n");
    printArray(arr, n);
    
    return 0;
}


Output:
1
2
In function 'printArray':
Line 7: error: 'for' loop initial declaration used outside C99 mode

If you compile the same program with option "-std=c99" or if you declare the variable i outside the for loop , it will work.

#include <stdio.h>
#include <string.h>

void printArray(char arr[], int n)
{
    int i;
    for(i=0; i<n; i++) {
        printf("%c ", arr[i]);
    }
    printf("\n");
}

int main()
{
    int n = 10;
    char arr[10] = "Shirley";

    printArray(arr, n);
    printf("Array before memset() arr %s and sizeof(arr) %d strlen(arr) %d\n", arr, sizeof(arr), strlen(arr));
    // Fill whole array with 0.
    memset(arr, '\0', sizeof(arr));

    
    return 0;
}

Output:
1
2
S h i r l e y    
Array before memset() arr Shirley and sizeof(arr) 10 strlen(arr) 7



Comments