我有以下代码
#include <iostream>
#include <cstdio>
volatile char s[7] = "test";
int main() {
std::cout << s << std::endl;
std::printf("%s\n", s);
}
它使用 std::cout 打印“1”,使用 std::printf 打印“test”。为什么第一种情况会打印“1”?!我的系统是“Linux debian 4.9.0-3-amd64 #1 SMP Debian 4.9.30-2+deb9u5 (2017-09-19) x86_64 GNU/Linux”,我的C++编译器是“g++ (GCC) 7.3.0” .
如果我删除“ volatile ”关键字,则 std::cout 会打印预期的“测试”。
最佳答案
printf
是可变参数,因此可以接受任何类型的参数。 cout
是更强类型的 C++ 东西。 char const volatile*
不会隐式转换为 char const*
。但它会转换为 bool
。因此是 1。
关于c++ - 将 volatile C 字符串与 std::cout 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49675369/