visual studio 是否允许您访问数组边界之外的内容? (VS2013)

Does visual studio let you access outside the bound of arrays? (VS2013)

我想要一个关于 visual studio C++ 的立场的正式解释,以及它在创建数组时的作用,例如:

int a[3] = {1, 2, 3};

然后你做类似的事情:

cout << a[4];

经测试,它会打印出存储在该内存位置的垃圾。为什么它允许程序员这样做,而像 javaScript 这样的语言会阻止用户这样做?

在 C++ 中不让编译器禁止用户进行这种行为的普遍理念是什么?这是从 C 继承下来的东西吗?

这些只是我的一些小好奇心,也许回答的人可以告诉我在哪里可以找到这些信息。 发生了什么 的答案不是我要问的,我感兴趣的是 为什么

谢谢。

它与编译器无关,但语言是以允许的方式定义的。它会导致未定义的行为,尽管内容是不确定

至于原因是允许的,考虑下标(数组索引)运算符的定义(来自ISO/IEC 14882:2011(E)§5.2 .1/1 [expr.sub]):

A postfix expression followed by an expression in square brackets is a postfix expression. One of the expressions shall have the type “pointer to T” and the other shall have unscoped enumeration or integral type. The result is an lvalue of type “T.” The type “T” shall be a completely-defined object type. The expression E1[E2] is identical (by definition) to *((E1)+(E2))

[强调我的]

由于上述原因,数组 E1 被衰减为指向第一个元素的指针(即它等同于 &(E1)[0]),然后编译器使用 (E1)+(E2)。由于数组已经衰减为指针,因此无法进行边界检查。