声明一个 int 变量

发布于 2024-11-01 18:27:42 字数 348 浏览 2 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

手心的温暖 2024-11-08 18:27:42

您可能使用 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)

花开浅夏 2024-11-08 18:27:42

第一个声明仅在 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 of i after the loop, this would in general be the case where you had a break clause in the loop and wanted to find out on which iteration you broke out of the loop.

断念 2024-11-08 18:27:42

我猜你在循环结束后使用了 i

曾几何时,代码的第一位与第二位相同,在循环外部范围内声明i,因此这样的代码是可能的:

for (int i = 0; i < size; ++i) {
    // do something
}

if (i != size) {
    // do something else
}

在标准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:

for (int i = 0; i < size; ++i) {
    // do something
}

if (i != size) {
    // do something else
}

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文