c++ - C++ - 循环初始化的奇怪问题
问题描述
编译器甚至无法处理最简单的循环
#include <iostream>
using namespace::std;
int main()
{
for( int i = 0, char a = 'A'; i <= 26; i++, a++ )
cout << "OK, lets try. Showing values: i = "
<< i << ", a = " << a << endl;
}
编译器这样说:
prog.cpp: In function ‘int main()’:
prog.cpp:7:18: error: expected unqualified-id before ‘char’
prog.cpp:7:18: error: expected ‘;’ before ‘char’
prog.cpp:7:39: error: expected ‘)’ before ‘;’ token
prog.cpp:7:41: error: name lookup of ‘i’ changed for ISO ‘for’ scoping [-fpermissive]
prog.cpp:7:41: note: (if you use ‘-fpermissive’ G++ will accept your code)
prog.cpp:7:46: error: ‘a’ was not declared in this scope
prog.cpp:7:50: error: expected ‘;’ before ‘)’ token
是的,我知道我可以在循环之前初始化“i”和“a”。所以让我们试试:
#include <iostream>
using namespace::std;
int main()
{
int i = 0;
for(i = 0, char a = 'A'; i <= 26; i++, a++ )
cout << "OK, lets try. Showing values: i = "
<< i << ", a = " << a << endl;
}
编译器说:
prog.cpp: In function ‘int main()’:
prog.cpp:8:13: error: expected primary-expression before ‘char’
prog.cpp:8:13: error: expected ‘;’ before ‘char’
prog.cpp:8:41: error: ‘a’ was not declared in this scope
当使用选项 -std=c++11 时:
prog.cpp: In function ‘int main()’:
prog.cpp:7:17: error: expected unqualified-id before ‘char’
prog.cpp:7:17: error: expected ‘;’ before ‘char’
prog.cpp:7:38: error: expected ‘)’ before ‘;’ token
prog.cpp:7:40: error: ‘i’ was not declared in this scope
prog.cpp:7:45: error: ‘a’ was not declared in this scope
prog.cpp:7:49: error: expected ‘;’ before ‘)’ token
最后一个:
#include <iostream>
using namespace::std;
int main()
{
int i = 0;
char a = 'A';
for(i = 0, a = 'A'; i <= 26; i++, a++ )
cout << "OK, lets try. Showing values: i = "
<< i << ", a = " << a << endl;
}
工作正常。伙计们,我是瞎了吗?也许你需要我的 Arch 和编译器版本:
uname -a
Linux freelancer 3.2.0-4-686-pae #1 SMP Debian 3.2.63-2+deb7u2 i686 GNU/Linux
g++ --version
g++ (Debian 4.7.2-5) 4.7.2
解决方案
您不能在同一声明中声明不同类型的项目。
在循环内部和外部都是如此。你不是“盲人”,它只是无效的 C++。
这是正确的代码:
#include <iostream>
using namespace::std;
int main()
{
int i = 0;
char a = 'A';
for(; i <= 26; i++, a++ )
cout << "OK, lets try. Showing values: i = "
<< i << ", a = " << a << endl;
}
您的工作版本也是有效的,因为可以将声明换成表达式,但在您的情况下它是多余的,因为这些变量已经在循环开始时保存了这些值。
推荐阅读
- java - servlet在tomcat上同时处理多个请求
- xamarin - Apk 文件不适用于 xamarin 表单 Android 中启用的 proguard
- google-cloud-platform - 从 Bigquery 中的行创建新列
- php - 用户多进程
- linux - 给定的shell命令有什么区别
- javascript - 单击时打开 v-date-picker v-menu 并将 v-text-field 聚焦在其中?
- amazon-web-services - 有没有办法在 aws cli 配置文件中指定 --endpoint-url
- r - 使用R时python中的子集问题
- ios - NavigationBar 的类别适用于 Xcode9,但不适用于 Xcode10
- sql - Postgres:计算期间的开始日期,以便间隔保持不变