Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
139 views
in Technique[技术] by (71.8m points)

c++ - Second FOR loop is being skipped

I am not getting any compile-time errors, but whenever i run the program the second FOR loop gets skipped and the program stops. i put a cout after it and that executed, but the second for loop was still skipped.

#include <iostream>

using std::cout;

int main()
{
    int numbers[5];
    for(int i; i < 5; i++)
    {
        std::cin >> numbers[i];
    }
    for(int i; i < 5; i++)
    {
        cout << numbers[i] << "";
    }
}
question from:https://stackoverflow.com/questions/65904892/second-for-loop-is-being-skipped

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When you write

 int i;

That declares an int named i without initializing it. Its value is said to be indeterminate. There is not much you can do with an indeterminate value, for example

int x = i;

invokes undefined behavior. When your code has ub then almost anything can happen. You could get no output at all, or some gibberish, or Hamlet printed on the screen (though this happens rarely).

You are not initializing the counter in both loops. That the first one appears to work is purely a matter of luck. Or rather bad luck, because appearing to work is the worst incarnation of wrong code.

Many guidelines suggest to initialize variables as soon as you declare them. Often this is put another way: Only declare a variable when you can initialize it. In any case, seeing int i; should make you shiver in fear ;).

Your loops should look like this:

for(int i=0; i < 5; i++)
{
    std::cin >> numbers[i];
}
for(int i=0; i < 5; i++)
{
    std::cout << numbers[i] << "";
}

On the other hand, if you want to iterate the whole container you can use a range based for loop which eliminates the chance for such mistake completely:

for(auto& n : numbers)
{
    std::cin >> n;
}
for(const auto& n : numbers)
{
    std::cout << n << "";
}

Note that use of initialized variables can be diagnosed by most compilers. With -Wall -Werror clang refuses to compile your code. Unfortunatly gcc fails to diagnose the issue in your code (while it quite reliably can diagnose cases such as int i; int x = i;). Hence, you should pay attention to warnings, and to make sure you cannot miss them you can treat them as errors.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...