一元&运算符在遇到[[]时的行为

问题描述 投票:0回答:1

我一直在阅读C11 6.5.3.2 p3

类似地,如果操作数是[]的结果运算符,不对&运算符或[]所隐含的一元*进行评估,并得出结果就像删除了&运算符,并将[]运算符更改为a +运算符一样。除此以外,结果是指向由其操作数指定的对象或函数的指针。

尽管反复阅读,但我听不懂本段的大部分内容。我的问题部分是* that is implied by the [][]operator were changed to a + operatorfunction designated by this operand。这一段是在谈论&,但是为什么出现[]后出现*,并出现“指定功能”一词。而且[] operator were changed to a + operator似乎试图说出数组的定义:E1[E2] = *((E1) + (E2))这些行是什么意思?我需要帮助。

c
1个回答
0
投票

如果操作数是一元*运算符的结果,则运算符和&运算符都被求值,结果就像除了对操作员的约束仍然适用之外,省略了并且结果不是左值。

将一元&应用于一元*的结果,取消*并将原始*的操作数转换为r值:

#include <assert.h>
int main()
{
    int *p=&(int){42};
    assert(&*p == p); //the value (42) is not fetched from the target
    #if 0
        &*p = &(int){1000}; //not OK; & cancels the * but converts p to an r-value (can't be on the left-hand side of an assignment)
    #endif
    p = &(int){1000}; //ok; p is an l-value (can be on the left hand side of an assignment)
    //(more accurately: can have its address taken)
}

现在,由于pointerOrArray[index]表达式被定义为6.5.2.1p2*(pointerOrArray+index)的结果,但隐藏了*,所以是一元*的结果),您可以对其应用相同的规则:[C0 ] <=> &pointerOrArray[index]。那就是你第一句被引用的句子。

您引用的最后一句话可以解释为(在(pointerOrArry+Index)中):

否则,如果一元6.5.3.2p3没有与&*组合,则(一元[]的结果是指向对象(&)或函数(&object)的指针由其操作数(&functionobject)指定。

© www.soinside.com 2019 - 2024. All rights reserved.