belle tian belle tian - 4 years ago 98
C++ Question

C ++ While statement and string handling confusion?

const char ca[] = {'h','e','l','l','o'};
const char *cp = ca;
// printf("%s\n",cp);
while(*cp) {
cout << *cp << endl;
++cp;
}


first it print:

h
e
l
l
o
// end


then I uncomment "printf" statement:

hello%s

h
e
l
l
o
%
s


// end


Why are the results so different?,how does the "While" condition exit(the exact value of *cp)?
C++ primer 5th page 110

Answer Source
while(*cp)

This loop condition is looping until it finds a NUL character. It's equivalent to:

while(*cp != '\0')

ca isn't NUL-terminated, so the loop runs off the end of the array and invokes undefined behavior. Undefined behavior means anything can happen.

To fix this, add a NUL terminator with

const char ca[] = {'h','e','l','l','o','\0'};

or, equivalently,

const char ca[] = "hello";

It appears that in the first case the loop ends right away because there happens to be a NUL byte in memory following the 'o'. But in the second case the "%s" string happens to be adjacent to ca and so that gets printed, too. "%s" is a proper NUL-terminated, so the loop ends after printing it.

The fact that an innocuous printf() call can change the behavior of an unrelated loop is an example of how unpredictable undefined behavior can be. It isn't always so benign. It could make your program crash. It could even make it continue working for a while and then misbehave later in a completely baffling way. Don't rely on undefined behavior behaving predictably.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download