我可以在 for 循环的初始化中声明不同类型的变量吗?
为什么这个 C++ 代码在 VS2010 下无法编译:
for ( int a = 0, short b = 0; a < 10; ++a, ++b ) {}
而这个却可以:
short b = 0;
for ( int a = 0; a < 10; ++a, ++b ) {}
for 循环初始化器中禁止声明两个不同类型的变量吗?如果是这样,你该如何解决这个问题?
Why does this C++ code not compile under VS2010:
for ( int a = 0, short b = 0; a < 10; ++a, ++b ) {}
while this one does:
short b = 0;
for ( int a = 0; a < 10; ++a, ++b ) {}
Is the declaration of two variables of different types inside the for-loop initializer prohibited? If so, how can you work around it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
是的,这是禁止的。正如其他情况一样,您不能在一个声明语句中声明不同类型的变量(编辑:以 @MrLister 提到的声明符修饰符为模)。您可以声明结构体
C++03 代码:
当然,当全部为
0
时,您可以完全省略初始值设定项并编写= { }
。Yes, that is prohibited. Just as otherwise you cannot declare variables of differing types in one declaration statement (edit: modulo the declarator modifiers that @MrLister mentions). You can declare structs
C++03 code:
Of course when all are
0
, you can omit the initializers altogether and write= { }
.与 for 循环无关。如果您在任何循环之外编写
int a = 0, Short b = 0;
,这也不会编译。所以答案是:总是禁止在一条语句中声明两个不同类型的变量。
编辑:哦,对于迂腐的人来说,我确实意识到您可以在同一语句中声明基类型和指针类型,例如 int 和 int 指针,所以它们将是不同的类型,是的。
嗯,这让我思考。在 32 位环境中,指针将是 4 个字节,就像 int 一样,因此您可以使用短 a = 0, *b = 0;然后将 b 转换为 int。嗯...
Nothing to do with the
for
loop. This also doesn't compile if you writeint a = 0, short b = 0;
outside of any loop.So the answer is: it is always forbidden to declare two variables of different types in a single statement.
Edit: Oh, for the pedantic, I do realise that you can declare a base type and a pointer type in the same statement, for instance an int and an int pointer, so those would be different types, yes.
Hm, that makes me think. In a 32 bit environment, a pointer would be 4 bytes, just like an int, so you could use short a = 0, *b = 0; and then cast b to an int. Hm...
禁止的是以逗号结尾的语句,就像 int a = 0, short ...
如果您想使用此表示法,则变量 muss 具有相同的类型
int i = 0, s = 0;
What is prohibited is the ending of a statement with a comma as you do in
int a = 0, short ...
If you want to use this notation then bothe variable muss have the same type
int i = 0, s = 0;
for 语句中只能声明一种类型。所以第二个代码是可用的。
You can only declare one type in for statement. So the second code is the usable one.
您不能在
for
(comprobation 步骤)的while
条件中声明变量。那都行不通。
You can't declare a variable into the
while
condition of thefor
(the comprobation step).that's neither works.