I have a question about a string in C++. As per below code, I would like to know where will the loops stop at. Will it take the null in index 3 or index 4?
#include <cstdio>
int main ( ) {
char name [20] = "Foo";
name [4] = '\0';
for (int i = 0; name[i] != '\0'; i++) {
printf("This is the value of i so far in the loop : %d \n",i);
}
printf("This is the value of i : %d \n",i);
return 0;
}
the reason I am asking this is,I don’t understand why in my homework they gave us something like this. Is there any reason to make ‘\0’ in index 4?
“Foo” is actually {‘F’,’o’,’o’,’\0′}, and fits index 0,1,2,3.
Index 4 up to 19 are default initialized (hence 0-ed). And index 4 is assigned later with ‘\0’.
The loop ends when the first ‘\0’ is matched, so that value 0,1,2 are printed.
Out of the loop
ishold … ahem .. be undefined! (it is declared inside the loop scope), but if your compiler didn’t clean up you most likely will print 3.A typycal example of C++ (note
#include<cstdio>, but no std never referenced…) taught by a C instructed teacher.Give my congrats to him!