【发布时间】:2018-09-15 10:53:10
【问题描述】:
我有以下代码
#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 会打印预期的“test”。
【问题讨论】:
-
我怀疑使用
volatile char*和%s是未定义的行为。