gpt4 book ai didi

c++ - 指针算法 - 编译器如何确定要递增的字节数?

转载 作者:行者123 更新时间:2023-12-01 14:22:53 26 4
gpt4 key购买 nike

考虑以下代码。

#include <iostream>

int main(){
int a[] = {1,2,3,4,5};
int b = 5;
std::cout << a[b] << std::endl;
std::cout << b[a] << std::endl;
}

我理解 a[b]b[a] 是相同的,正如标准所规定的那样:

Except where it has been declared for a class (13.5.5), the subscript operator [] is interpreted in such a way that E1[E2] is identical to *((E1)+(E2)). Because of the conversion rules that apply to +, if E1 is an array and E2 an integer, then E1[E2] refers to the E2-th member of E1. Therefore, despite its asymmetric appearance, subscripting is a commutative operation.

不过,我还是不太明白。编译器确实以字节为单位进行寻址运算。由于一个int占用4个字节,所以a[b]b[a]都会被翻译成*(a + b * 4) .我的问题是:编译器如何确定正确的翻译是*(a + b * 4),而不是*(b + a * 4)?当编译器以 E1[E2] 形式给出表达式时,编译器可以将其翻译成 *(E1 + E2 * 4) *(E2 + E1 * 4) - 编译器如何知道哪一个是正确的选择?

最佳答案

决定因素类型不是对象的大小。它是对象的实际、完整类型。

编译器知道每个对象的实际类型。编译器不仅知道 a 是四个字节(在 64 位系统上是八个字节),而且它是一个指针,而 b 是一个整数类型。这是 C++ 的一个基本方面:每个对象的类型在编译时是并且必须是已知的。

因此,当将指针类型添加到整数类型时,整数值会乘以所指向类型的大小。哪个在+ 运算符的左侧和右侧并不重要。如果一个操作数是指针,而另一个是整数类型,这就是 C++ 中发生的情况。

关于c++ - 指针算法 - 编译器如何确定要递增的字节数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61691156/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com