下面的程式中,在for迴圈,區域變數index應該宣告初始值,但是沒有宣告。
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
@autoreleasepool {
for (int index; index < 10; index++) {
NSLog(@"index = %d", index);
}
// insert code here...
NSLog(@"Hello, World!");
}
return 0;
}
2014-03-19 10:12:22.971 forloop[679:303] index = 0
2014-03-19 10:12:22.973 forloop[679:303] index = 1
2014-03-19 10:12:22.974 forloop[679:303] index = 2
2014-03-19 10:12:22.974 forloop[679:303] index = 3
2014-03-19 10:12:22.975 forloop[679:303] index = 4
2014-03-19 10:12:22.975 forloop[679:303] index = 5
2014-03-19 10:12:22.976 forloop[679:303] index = 6
2014-03-19 10:12:22.976 forloop[679:303] index = 7
2014-03-19 10:12:22.977 forloop[679:303] index = 8
2014-03-19 10:12:22.977 forloop[679:303] index = 9
2014-03-19 10:12:22.978 forloop[679:303] Hello, World!
Program ended with exit code: 0
顯然編譯器自動給予初始值0,如果原本想要的初始值是1,那麼結果就非如預期了。
無論如何,在for迴圈中,區域變數一定要有初始值,否則程式會出現不可預期的結果。
沒有留言:
張貼留言