开发者

declaring an int variable

开发者 https://www.devze.com 2023-02-25 01:57 出处:网络
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.
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 somebod开发者_StackOverflow社区y 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.


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)


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消