字符串末尾的额外零字符出现在 C++ 中用于范围循环

Alb*_*ble 8 c++ string for-loop char

以下代码

#include <iostream>
#include <string>
int main()
{
    std::string s = "abc";
    for (char c : s)
        std::cout << (int) c << " ";
}
Run Code Online (Sandbox Code Playgroud)

打印“97 98 99”。

以下代码

#include <iostream>
int main()
{
    for (char c : "abc")
        std::cout << (int) c << " ";
}
Run Code Online (Sandbox Code Playgroud)

打印“97 98 99 0”。

第二个代码中额外的 0 来自哪里?

Bat*_*eba 10

文字"abc"是一种const char[4]类型:最后一个元素是 NUL 终止符(值为 0)。

在第二个片段中,当代码描述对整个const char[4]数组的迭代时,会打印 NUL 终止符的值。

在第一个片段中,类的底层迭代器技术std::string将结束迭代器(在短形式for循环中未达到)设置为 NUL 终止符。这种行为与s.size().