I'll preface this question by saying I am knowledgeable on C, and I'm learning C++.
Suppose I've got an std::string object and I want to go thru all of its characters to verify it (for example, only 4 letters allowed).
I have seen for (type var : array)
being used in some code around a week ago, but I couldn't remember how it was used. I'm wondering.. exactly how does this work, and why does it work? Logically it shouldn't.
AFAIK, arrays don't really "know" what their length is. So suppose I have this code:
int arr[] = { 1, 2, 3 };
for (int item : arr) {
std::cout << item << std::endl;
}
How the hell does the for loop
know when to stop? Arrays are simply put allocated memory (stack, in this case) that start from a specific address and go on. There's no "stored length" (AFAIK) for arrays. This is why it is a programmer's responsibility to store the length of the array, and do for (int i = 0; i < [length]; i++)
but this somehow works?
Would love some explanation. Specific use case for my code:
std::string test = "Hello World!";
for (char letter : test) {
if (letter == 'l') {
std::cout << "'l' exists!" << std::endl;
} // result should be 3 prints.
}