5

I have this c file

#include <stdio.h>

int main(int argc, char *argv[])
{
  int x,i,sum;
  sum = 0;
  FILE *fin;
  fin = fopen("testdata1", "r");


    for (i = 0; i < 20; i++ ){
      fscanf(fin, "%d", &x);
      sum += x;
    }

    printf("Sum = %d", sum);
    fclose(fin);
    return 0;


}

I compiled it via gcc -ansi -pedantic -Wall app.c -o app

While compiling, I kept getting this warning error

warning: ISO C90 forbids mixing declarations and code [-Wdeclaration-after-statement] FILE *fin; ^ 1 warning generated.

Any hints on how do I stop that ?

Paul Rooney
  • 20,879
  • 9
  • 40
  • 61
code-8
  • 54,650
  • 106
  • 352
  • 604

1 Answers1

11

This is because in C89/C90, you have to first declare (eventually initialize) your variables, then put your code. Here is the highlighted problem:

int x,i,sum;
sum = 0; // This is code!
FILE *fin;

First solution is to initialize sum in the declaration:

int x,i,sum = 0;

Second solution is to initialize sum in the beginning of the code:

int x,i,sum;
FILE *fin;

sum = 0;
fin = fopen("testdata1", "r");

Third solution is to compile using another standard. With gcc/mingw, this is achieved by passing the command-line option -std=<your standard>, for example, -std=c99 or -std=c11 (and remove -ansi).

Cakeisalie5
  • 384
  • 3
  • 10