简体   繁体   中英

What's the difference between “ABC” and string(“ABC”) in C++?

I have the following code snippet...

for(char c: "ABC") cout << c << endl;
for(char c: string("ABC")) cout << c << endl;

The second one works fine. But's first one behaves different in different environment. What's the difference between these two?

"ABC" is a string literal with type const char[4] , ie an array containing 4 char s including the terminating null character '\\0' . for(char c: "ABC") cout << c << endl; would output all the 4 elements.

string("ABC") is of type std::string constructed to contain only 3 elements, for(char c: string("ABC")) cout << c << endl; would output the 3 elements, 'A' , 'B' , and 'C' .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM