简体   繁体   中英

Why doesn't this while loop end?

I copied this code from C++ Primer as an example for while loops, and it doesn't output anything. I'm using g++.

#include <iostream>

int main()
{
    int sum = 0, val = 1;
    // keep executing the while as long val is less than or equal to 10
    while (val <= 10) {
        sum += val;     // assigns sum+ val to sum\
        ++val;          // add 1 to val
    }
    std::cout << "Sum of 1 to 10 inclusive is "
              << sum << std::endl;
    return 0;
}
sum += val;     // assigns sum+ val to sum\

Get rid of the backslash at the end of the line. That's a line continuation character. It causes the next line to be concatenated to this line; in other words, ++val becomes part of the "assigns sum+ val to sum" comment.

    sum += val;     // assigns sum+ val to sum\ <-- typo
    ++val;          // add 1 to val

You got a typo at that sum += val; line. The "\\" at the end make the following line a comment, thus making the while an infinite loop as val was never increased. Remove "\\", then it would work.

这是一个简单的错误,在注释“//将sum + val加到sum之后”后删除\\。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM