为什么C ++允许使用负索引和大于数组长度减1的索引进行索引? [英] Why does C++ allow indexing with negative indices and indices larger than the length of the array minus 1?

查看:53
本文介绍了为什么C ++允许使用负索引和大于数组长度减1的索引进行索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么编译器不会阻止我使用大于数组长度的整数减去一和负整数来索引到数组中?

Why doesn't the compiler stop me from indexing into an array using integers greater than the length of the array minus one and negative integers?

允许这样做的理由是什么?

What is the rationale behind allowing this?

推荐答案

编译器不能这样做,因为这是运行时的规定.

Well the compiler can't because that's a runtime provision.

但是为什么 std :: vector 没有界限检查 [] 运算符.这是因为已经有一个边界检查方法 at().这将执行边界检查,如果索引超出边界,则会引发异常.

But why does the std::vector not bounds check the [] operator. This is because there is already a bounds checked method at(). This performs bounds checking and throws an exception if the index is out of bounds.

但是不付不使用的钱的C ++原则也在起作用.如果您已经保证它在范围之内,为什么还要检查一个超出范围的异常.

But the C++ principle of not paying for what you don't use is also at play. Why should you check for an out of bounds exception if you have already guaranteed it is in bounds.

for(int loop = 0; loop < cont.size(); ++loop) {
    std::cout << cont[loop] << "\n";   // Do I need to bounds check here?
}                                      // loop is guaranteed to be in range
                                       // why should I pay for the cost of
                                       // of a check? So beginners don;t make
                                       // mistakes?

因此,如果要限制检查的访问权限,请使用 at();如果要取消检查的访问权限,请使用 [] .

So if you want bounds checked access use at() if you want unchecked use [].

从评论中:

p [-10] 为什么起作用?因为在指针类型上,这只是 *(p-10)的语法糖.您会认为,要检查其有效性要困难得多.

Why does p[-10] work? Because on pointer types this is simply syntactic sugar for *(p - 10). That a lot harder to check for validity then you think.

int  q[] = {1,2,3,4,5,6,7,8,9,10,11,12,13};
int* p   = q + 11;

std::cout << p[-10]; // This is valid operation.

这篇关于为什么C ++允许使用负索引和大于数组长度减1的索引进行索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆