gpt4 book ai didi

c - 又一个序列点查询 : how does *p++ = getchar() work?

转载 作者:太空狗 更新时间:2023-10-29 15:45:58 26 4
gpt4 key购买 nike

§5.1.2.4.16

EXAMPLE 7 The grouping of an expression does not completely determine its evaluation. In the following fragment:

#include <stdio.h>
int sum;
char *p;
/*
...
*/
sum = sum * 10 - '0' + (*p++ = getchar());

the expression statement is grouped as if it were written as

sum = (((sum * 10) - '0') + ((*(p++)) = (getchar())));

but the actual increment of p can occur at any time between the previous sequence point and the next sequence point (the ; ), and the call to getchar can occur at any point prior to the need of its returned value.

所以基本上我将其理解为未指定的行为 - *p = getchar(); p++;p++; *p = getchar()。请注意,; 表示一个序列点,但整个表达式中没有其他序列点。

所以这个语法是没用的。而且,几乎,++ 和 -- 对于指针赋值是无用的。 对吧?

最佳答案

either *p = getchar(); p++; OR p++; p* = getchar() [sic]

其实没有。它是:

*p = getchar(); p++

old_p = p++; *old_p = getchar()

在您的解释中,您可以写在 *p*(p + 1) 处,但这是不正确的。在这两种解释中,您都写入了 p 最初指向的位置,而不管编译器何时决定放置更改 p 的指令。如果它决定将它放在写入 *p 之前,那么它必须确保保留旧值以便稍后写入 (*old_p)。

后缀 --++ 运算符实际上是非常好的快捷方式。举个例子:

size_t strlen(const char *str)
{
size_t len = 0;
while (str[len++]);
return len - 1;
}

这是strlen的一个非常简洁的实现,使用后缀++


来自 C11,6.5.2.4.2(强调我的):

The result of the postfix ++ operator is the value of the operand. As a side effect, the value of the operand object is incremented (that is, the value 1 of the appropriate type is added to it). See the discussions of additive operators and compound assignment for information on constraints, types, and conversions and the effects of operations on pointers. The value computation of the result is sequenced before the side effect of updating the stored value of the operand. With respect to an indeterminately-sequenced function call, the operation of postfix ++ is a single evaluation. Postfix ++ on an object with atomic type is a read-modify-write operation with memory_order_seq_cst memory order semantics.

关于c - 又一个序列点查询 : how does *p++ = getchar() work?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16275813/

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