初始化顺序:具有指向同一数组的单独指针的数组
Initialization order: An array with a separate pointer to that same array
我有一行代码声明了一个char
的静态数组,像这样:
char buf[7];
我想用指针遍历这个数组,但是buf
本身显然不能自增自减。我的问题基本上是,这是合法的,还是这种未定义的行为:
// Does this guarantee ptr == buf?
char buf[7], *ptr = buf;
// ... because if not, then this could crash my program!
std::cout << *ptr << '\n';
这个例子和类似的例子编译 运行 在我的电脑(WSL,gcc 9.3.0)上使用所有优化标志都很好。在每次测试中,我 运行、buf == ptr
。但从技术上讲,C++ 标准是否允许编译器重新排序这些声明,以便将 ptr 初始化为一些垃圾值?
我显然可以将其分成两行以避免任何疑问,但我想知道这一行声明是否有效。
is this legal
是
is this undefined behavior
没有
would the compiler be allowed by the C++ standard to reorder these declarations so that ptr is initialized to some junk value?
不,它用 buf
衰减成的 char*
初始化 ptr
。如果允许编译器以其他顺序初始化它们,则它需要编译失败,因为它还没有看到 buf
。
与这些比较:
确定:
char buf[7];
char *ptr = buf;
错误:
char *ptr = buf;
char buf[7];
我有一行代码声明了一个char
的静态数组,像这样:
char buf[7];
我想用指针遍历这个数组,但是buf
本身显然不能自增自减。我的问题基本上是,这是合法的,还是这种未定义的行为:
// Does this guarantee ptr == buf?
char buf[7], *ptr = buf;
// ... because if not, then this could crash my program!
std::cout << *ptr << '\n';
这个例子和类似的例子编译 运行 在我的电脑(WSL,gcc 9.3.0)上使用所有优化标志都很好。在每次测试中,我 运行、buf == ptr
。但从技术上讲,C++ 标准是否允许编译器重新排序这些声明,以便将 ptr 初始化为一些垃圾值?
我显然可以将其分成两行以避免任何疑问,但我想知道这一行声明是否有效。
is this legal
是
is this undefined behavior
没有
would the compiler be allowed by the C++ standard to reorder these declarations so that ptr is initialized to some junk value?
不,它用 buf
衰减成的 char*
初始化 ptr
。如果允许编译器以其他顺序初始化它们,则它需要编译失败,因为它还没有看到 buf
。
与这些比较:
确定:
char buf[7];
char *ptr = buf;
错误:
char *ptr = buf;
char buf[7];