warning: ISO C90 forbids mixing declarations and code [-Wdeclaration-after-statement] [duplicate]

非 Y 不嫁゛ 提交于 2021-02-07 17:54:00

问题


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 ?


回答1:


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).



来源:https://stackoverflow.com/questions/42262965/warning-iso-c90-forbids-mixing-declarations-and-code-wdeclaration-after-state

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!