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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…