声明一个 int 变量
for(int i=0; i < size; i++)
我在上面的代码中声明了一个变量,但收到了一个编译时错误:根据 ISO 标准,类似这样的声明已经过时了。
然后我像这样在 for 循环外部声明了变量
int i;
for(i=0; i < size; i++)
......并且它起作用了???
有人可以告诉我这个声明吗,因为据我所知,在 C++ 中,我们不仅可以像 c 中那样在顶部声明变量,而且可以在需要时在下面的任何地方声明变量。
我使用的编译器是gcc。
for(int i=0; i < size; i++)
I declared a variable in my code as above an received a compile-time error: something like such a declaration is obsolete according to ISO standards.
Then I declared the variable outside the for loop like this
int i;
for(i=0; i < size; i++)
.......and it worked????
Can somebody tell me about this declaration because as far as i know in C++ we can declare the variable not just at the top as in c but anywhere below while we need it.
The compiler that I was using is gcc.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可能使用 gcc 而不是 g++ 进行编译(或 xl_C 而不是 xl_C++ 等)。
否则,请检查您是否通过了旧标准(使用 -std=c89 或 -ansi)
You were probably compiling with gcc instead of g++ (or xl_C instead of xl_C++ etc.)
Otherwise, check that you are not passing an old standard (with -std=c89 or -ansi)
第一个声明仅在 for 循环的范围内声明
i
。第二个在紧邻外部的范围内声明它。两者都是完全有效的。当您想在循环后使用i
的值时,您可以使用第二种情况,通常是在循环中有一个break
子句并且想要找出您在哪一次迭代中打破了循环。The first declaration declares
i
only in the scope of the for loop. The second declares it in the scope immediately outside. Both are perfectly valid. You would use the second case when you want to use the value ofi
after the loop, this would in general be the case where you had abreak
clause in the loop and wanted to find out on which iteration you broke out of the loop.我猜你在循环结束后使用了
i
。曾几何时,代码的第一位与第二位相同,在循环外部范围内声明
i
,因此这样的代码是可能的:在标准C++中,这是无效的;
i
仅在循环体中可用,您需要在循环外声明它才能在循环体中访问它。I will guess that you are using
i
after the loop ends.Once upon a time, the first bit of code was equivalent to the second, declaring
i
in the scope outside the loop, so code like this was possible:In Standard C++, this is invalid;
i
is only available in the body of the loop, and you need to declare it outside the loop to access it there.