0

我已经按照本网站上的参考指南的建议浏览了 c++ 入门书,我注意到作者省略了 for 循环的花括号。我检查了其他网站,通常应该放入花括号。放置花括号并省略它时会出现不同的输出。代码如下

int sum = 0;
for (int val = 1; val <= 10; ++val)
    sum += val;  
    std::cout << "Sum of 1 to 10 inclusive is " << sum << std::endl;

// This pair of code prints the std::cout once
for (int val = 50; val <=100;++val)
    sum += val;
    std::cout << "Sum of 50 to 100 inclusive is " << sum << std::endl;

// -------------------------------------------------------------------------
for (int val = 1; val <= 10; ++val) {
    sum += val;  
    std::cout << "Sum of 1 to 10 inclusive is " << sum << std::endl;
}

// This pair of code prints the std::cout multiple times
for (int val = 50; val <=100;++val) {
    sum += val;
    std::cout << "Sum of 50 to 100 inclusive is " << sum << std::endl;
}

如果有人能解释输出的差异,我将不胜感激。提前致谢!

4

2 回答 2

3

for 语句特别定义如下

for ( for-init-statement conditionopt; expressionopt) statement
                                                      ^^^^^^^^^

其中语句可以是任何语句,包括复合语句

compound-statement:
    { statement-seqopt}

因此在这个 for 语句的例子中

for (int val = 1; val <= 10; ++val)
sum += val; 

声明是

sum += val; 

而在这个 for 语句的例子中

for (int val = 1; val <= 10; ++val) {
sum += val;  
std::cout << "Sum of 1 to 10 inclusive is " << sum << std::endl;
}

声明是

{
sum += val;  
std::cout << "Sum of 1 to 10 inclusive is " << sum << std::endl;
}
于 2016-01-18T21:24:19.577 回答
0

使用花括号,大括号中的所有内容都由 for 循环执行

for (...;...;...)
{
     // I get executed in the for loop!
     // I get executed in the for loop too!
}
// I don't get executed in the for loop!

但是,如果没有花括号,它只会在它之后直接执行语句:

for (...;...;...)
     // I get executed in the for loop!
// I don't get executed in the for loop!
// I don't get executed in the for loop either!
于 2016-01-18T21:22:14.940 回答