c++ - What's the difference between an empty string and a '\0' char? (from a pointer and array point of view) -


as title of question? what's difference?

if write:

char *cp = "a"; cout << (cp == "a") << endl; 

or:

string str = "a"; cout << (str == "a") << endl; 

they same , return true. if write:

char *cp = ""; cout << (cp == "\0") << endl; 

it returns false. but:

string str = ""; cout << (str == "\0") << endl; 

it returns true.

i thought should same pointer , array perspective. turn out different. what's subtle difference between them? , how should write char array represent empty string?


ok, what's above line might unclear said might "a compiler optimization".

what want this:

char *cp = "abcd"; 

can give me array this: ['a', 'b', 'c', 'd', '\0']. wondering how can use similar syntax array this: ['\0']. because tried:

char *cp = ""; 

and seems not right code. thought give me want. doesn't.

sorry ambiguousness above line. i'm newbie , don't might compiler optimization.

string literals have implicit \0 @ end. "" of type const char[1] , consists of 1 \0, whereas "\0" of type const char[2] , consists of two \0s. if want empty string literal, write "". there no need insert \0 manually.

operator==(const char*, const char*) compares pointers, not characters. if compare 2 different string literals ==, result guaranteed false. (if compare 2 string literals consisting of same characters ==, result not well-defined.)

std::string::operator==(const char*) treats argument c string. is, read until encounters first \0. hence, cannot distinguish between "" , "\0".


Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -