12

Is this code fragment OK or does it result in undefined behavior?

std::string s; assert(strlen(s.c_str())==0); 

If it isn't undefined behavior, will the above assertion pass?

3 Answers 3

13

That is perfectly well defined and the assertion passes. The c_str() function will always return a valid zero terminated C string.

One would normally use empty() to test for an empty string.

Sign up to request clarification or add additional context in comments.

Comments

6

Yes it will work (if you append () to c_str to make it actually call the function) and the assertion will pass.

Comments

3

It's a compile error (if you have assertions enabled), since a const char *(std::string::*)(), cannot be converted to const char * implicitly.

(Tongue only halfway in cheek.)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.