char string[80];
cout << "Enter a stirng : " ;
cin.getline(string, 79);
int len;
for(len = 0; string[len] != '\0'; len++);
int i, j, flag = 1;
for(i = 0, j=0; i<len/2; i++, j--) { // I don't know this part
if(string[i] != string[j]) {
flag = 0;
break;
}
}
at the beginning, the for loop exam the string[0] != string[0], and next string[1] != string[-1], I don't understand what this meaning ,why in the beginning exam the two same char, and next exam the negetive index???
Perhaps to you, but when someone unfamiliar looks at the code and sees your for loop they will automatically know, oh J = 0 (they can pretty much skim past it). But if you put len-1, they will have to go back up and read what len is, why J is being put at len-1 and how len is used...
This is just me looking at it. It appears easier to read when J=0 from an outsider and not having to re-look at the same code twice...
Side Note: Most people, not all, do like to make things easier to read for everyone to understand, especially on bigger projects which multiple people are working. This way it's uniformly the same to everyone and not just easily read by one person.
Hi, Edwards.
Though it's easier to read the j = 0; but what does j = 0; mean? in the for loop, first compare the string[0] != string[0]; and next loop, the index will be negative, what does this mean? I don't know what the negative index mean. Can you tell me?
Hi, ResidentBiscuit. I also think j = len -1 makes more sense, but I saw the video in YouTube, he use the j = 0, I can't understand, but when I use j = 0; to exam it, it works.(also j = len -1 works). I really wonder why
It is legal to index an array with a negative index, but you should remember that indexing an array is always equivalent to *(array+index). If that causes you to access memory that is out of the bounds of the array, it results in undefined behavior as it does in the code in the original post.
but why it works?
It doesn't. The appearance of working and working are different things.
guestgulkan, you have a amazing memory, yeah, the guy using VS 2010 Express, and I use the VS 2010 Ultimate, can VS 2010 work with negative index?
I write a code in VS like this:
Now, hold on a minute - char string[80];
and string s = "xxxxx";
are completely different. std::string will have its own behavior for the [] operator because it overloads it. The character array string will have the compiler's behavior.
No, the character array will have the behavior described by the standard. Which is to say memory out of bounds will be accessed and the behavior is undefined.