gpt4 book ai didi

c++ - 指针和后增量搞笑业务

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:51:37 25 4
gpt4 key购买 nike

如果有的话,这个 c/c++ 语句在理论上有什么错误:

*memory++ = BIT_MASK & *memory;

其中 BIT_MASK 是任意按位 AND 掩码,memory 是一个指针。

目的是读取一个内存位置,AND 带有掩码的值,将结果存储在原始位置,最后递增指针以指向下一个内存位置。

最佳答案

您正在调用未定义的行为,因为您在没有中间序列点的单个语句中两次引用 memory(一次用于读取,一次用于写入),并且语言标准没有指定增量何时会发生。 (您可以多次读取相同的内存;当您尝试将一些写入与读取混合时会出现问题 - 如您的示例所示。)

您可以使用:

*memory++ &= BIT_MASK;

在不引起未定义行为的情况下实现您想要实现的目标。


在 C 标准(ISO/IEC 9899:1999 又名 C99)中,§6.5“表达式”,¶2 说

Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be read only to determine the value to be stored.70)

这是 C 标准中的主要来源。脚注说:

This paragraph renders undefined statement expressions such as

i = ++i + 1;
a[i++] = i;

while allowing

i = i + 1;
a[i] = i;

此外,'Annex C (informative) Sequence Points' 对所有这些都有广泛的讨论。

您会在 C++ 标准中找到类似的措辞,但我不确定它是否与“附件 C”类似。

关于c++ - 指针和后增量搞笑业务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8298223/

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