c - 重新定义 'i'错误

标签 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 += ceil(dist(wallSegments[i+0], wallSegments[i+1], wallSegments[i+2], wallSegments[i+3]) / dWallPoints) - 2;
  // other stuff here
}

当我尝试编译时,出现以下错误。来自 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

最佳答案

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

在标准 C 1999 和更高版本(C99 和 C11)中,允许在循环本身中声明一个变量,此外,作用域只是循环,就像在 C++ 中一样。

通过使用一些现代 C 方言进行编译,您的代码必须能够正常运行。

我使用带有选项 -std=c99(或 c11)的 GCC。
在这种情况下,您的代码对我来说很顺利。

关于c - 重新定义 'i'错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26153179/

相关文章:

java - 将字符串更改为 Char 数组

java - JBACI java编译错误

C-函数隐式声明时间,rand,printf,我所有的函数调用

c - 算术溢出,因为 C 程序中有符号字符

javascript - 计算 2 个数组中的每个值,如果每个数组的长度不相同,则推送长度较长的值

iOS:<未知>:0:错误:未知参数: '-enable-batch-mode' 命令 CompileSwiftSources 失败,退出代码非零

c# - 为什么List.Add即使存在对象也返回错误 'Object reference not set to an instance of an object'?

c - 传递结构指针与传递结构

c - addr2line 打印 "??:0"即使我使用 `gcc -g`

c++ - 我正在尝试使用 vector 迭代器创建一个 for 循环