I'm a beginner in C++ and trying to get my head around every new concept I come across by writting as many various little programs (programmlets) as possible. So I've just concocted the following piece of code:
#include <iostream>
using namespace std;
int main(){
int inumbers[] = {1 ,2 , 3, 4, 5};
int *p;
int i;
p = inumbers;
for(i = 0; p[i]; i++) cout << p[i] << '\n';
return 0;
}
And I fail to understand a seemingly simple thing: how does a compiler "know" when to stop incrementing the loop variable "i"? Surprisingly, the code does work the way it was supposed to.
The compiler does not know when to stop.
for(i = 0; p[i]; i++)
will only stop when p[i]
is 0
. You just got lucky and p[5]
happened to be 0
. There is nothing saying that it has to be so and it could keep going like this example. As soon as i >= array size
you are accessing memory the array does not own and you enter the world of undefined behavior.
Also if you had a 0
in the array like
int inumbers[] = {1 ,2 , 0, 4, 5};
then the program will only print
1
2
And it will not visit the rest of the array.
When dealing with an array or a standard container you can use a ranged based for loop like
for (const auto & e : inumbers)
std::cout << e << '\n';
To iterate through it's contents. Then const &
is not really needed in this case as we are dealing with an int but it is a good habit to get into as passing by reference avoids copying and making it const
prevents you from accidentally modifying the element when doing a read only operation.
When dealing with a pointer you need to provide a size like
for (int i = 0; i < size_of_pointed_to_array, i++)
std::cout << p[i] << '\n';
You got lucky. By random chance, it appears that there was a zero in memory after the last element in your inumbers
array.
Your program is not actually correct. Instead, you might want to limit your loop by counting array members:
for(i = 0; i < sizeof(inumbers)/sizeof(int); i++) cout << p[i] << '\n';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With