Ryan
Ryan

Reputation: 199

Error: 'for' loop initial declarations are only allowed in c99 mode

I've got this problem where I can only compile using the gcc -std=c99 but however, i need it to compile using c89 aka gcc -Wall. This is part of my code where i use the 'for' loop. Please see if you can help me out thank you in advance.

#include<stdio.h>
int main()
{
    int arr[100],i=0,ch;
    int n = 1, sum = 0;
    printf("Check out our selection! \n");
    printf("Airhead - 25 cents\n");
    printf("Fun Dip - 40 cents\n");
    printf("Gummi Bears - 20 cents\n");
    while (n != 0)
    {
        printf("Insert Coins: ");
        scanf("%d",&n);
        arr[i++] = n;
    }

    for(int j=0;j<i;j++)
    {   sum = sum + arr[j];
    }
......

Upvotes: 0

Views: 6675

Answers (1)

unalignedmemoryaccess
unalignedmemoryaccess

Reputation: 7441

This is wrong:

for (int j = 0; j < i; j++) {
    sum = sum + arr[j];
}

You have to initialize j in beginning of function.

 int main() {
    int j;
    ...
    for (j = 0; j < i; j++) {
        sum = sum + arr[j];
    }
}

Upvotes: 3

Related Questions