C 重新定义';i';错误

C 重新定义';i';错误,c,for-loop,compiler-errors,C,For Loop,Compiler Errors,因此,我有以下C代码: for (int i = 0; i < nWallSegments; i+=4) { fscanf(fin, "%le %le %le %le", &wallSegments[i+0], &wallSegments[i+1], &wallSegments[i+2], &wallSegments[i+3]); } for (int i = 0; i < nWallSegments; i+=4) { nWallPoints

因此,我有以下C代码:

for (int i = 0; i < nWallSegments; i+=4) {
  fscanf(fin, "%le %le %le %le", &wallSegments[i+0], &wallSegments[i+1], &wallSegments[i+2], &wallSegments[i+3]);
}

for (int i = 0; i < nWallSegments; i+=4) {
  nWallPoints += ceil(dist(wallSegments[i+0], wallSegments[i+1], wallSegments[i+2], wallSegments[i+3]) / dWallPoints) - 2;
  // other stuff here
}
for(int i=0;i
当我试图编译时,我得到以下错误。来自Python的背景,我不知道发生了什么。我在网上搜索过答案,但没有找到

Prog.c:44:12: error: redefinition of 'i'
  for (int i = 0; i < nWallSegments; i+=4) {
           ^
Prog.c:40:12: note: previous definition is here
  for (int i = 0; i < nWallSegments; i+=4) {c
Prog.c:44:12:错误:重新定义“i”
对于(int i=0;i
“对“我”的重新定义”。在同一范围内定义变量
i
两次。在C中不能这样做。删除第二个
int
,应该可以。

在ANSI C89中,不能在for循环内声明
i
。在for循环外声明一次。

这取决于编译器和/或标准C的版本

标准C 1999和以后(C99和C11),它可以在循环中声明变量,而且,范围仅是循环,如C++中的。 通过使用一些现代C方言进行编译,您的代码必须运行良好

我使用GCC选项-std=c99(或c11)。

在这种情况下,您的代码对我来说很好。

因此,如果我在for声明中声明
I
,则范围在for循环之外?如果您在for循环内声明它,它将不会在许多编译器(包括默认gcc)上编译。@VedaadShakib否,您的代码在C99中是合法的,但您使用的是C89编译器。在C89中,变量必须声明为I“我是在使用GNU的GCC。@ VEDAADHAKIB B GCC默认使用GNU扩展C89。尝试添加<代码> -STD= C99 < /Cord>选项。如果在声明中声明“代码> i <代码>,则在for循环之外。是的,在C++中的C.,范围是循环。不正确。在C89中,对于的<<代码>循环中有一个范围,类似C++。OP使用GCC(默认模式)的<代码> GNU89<代码>模式,它允许在for循环中定义
int i
,但它将其放入封闭范围,而不仅仅是循环的范围。谢谢!我发现这个问题是因为我经历了新的语义,并对它为什么没有给出错误感到困惑。我只是想得太多了。