-3

For the sake of me better understanding C++ strings, array and pointers; I want to know: Why is it that I can use a condition whereby I check if the index has reached the null-terminating character like this...

const char* myString = "Grandopolous";
for (int i = 0;;i++)
{
    if (!myString[i])
        break;
    else
        cout << myString[i];
}

So that works just fine. Here I am instead checking to see if the character equals something other than the null-terminating character and so I expect that if it doesn't the result should be not 0 and the condition should be true. but this does not work, and I simply cannot fathom why:

const char* myString = "Grandopolous";
for (int i = 0;;i++)
{
    if (myString[i])
        cout << myString[i];
}

This does not work on my machine and crashes, also it outputs a lot of unreadable error messages mixed with strange symbols. I don't think that part matters although it is the first time error have been printed to my console application instead of the debug console.

The reason I mentioned pointers is because I managed to get the condition to work using pointers instead of the array index syntax which I find much easier to read.

So could someone please help me understand why my first bit of code is valid and why my second is not.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
K.Roe
  • 33
  • 8

1 Answers1

2

It does work. The check for null isn't the problem.

Your program crashes because you got rid of the break so your program overruns the array then continues forever into the abyss.

Your debugger would surely have revealed this to you as you stepped through the program, observing i.

To reverse the logic of your first example, write:

const char* myString = "Grandopolous";
for (int i = 0;;i++)
{
    if (myString[i])
        cout << myString[i];
    else
        break;
}
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • 1
    Oh Thank You I was so confused I knew it had to be something so silly I was doing. – K.Roe May 08 '17 at 09:38
  • 1
    Or even (in this case) move the test where it belongs: `for (int i = 0; myString[i]; ++i) { std::cout << myString[i]; }`. – Toby Speight May 08 '17 at 15:00
  • Thanks that is really something i never though about I will do that in the future. @TobySpeight – K.Roe May 09 '17 at 14:47