I found the following piece of code embedded in a C++ project. The code goes backwards through a C-style string. When I saw this I thought this should result in undefined behaviour. But it seems to work perfectly:
const char * hello = "Hello World.";
const char * helloPointPos = strchr(hello, '.');
for (const char * curchar = helloPointPos; *curchar; curchar--) {
printf("%s", curchar);
}
What I was wondering about is the part with *curchar; curchar--
. This assumes that the string begins with a \0. Is this a legal assumption? Does this piece of code result in undefined behaviour? If not, why not?
I would appreciate if you could put some light on this. BTW platform is Windows and Compiler is VC++ 2010.
EDIT : Thank you all for your participation. Both answers are very good and helped me. But since I can only accept one answer I will go for paxdiablo's answer since it has more detail. Thank you!