gpt4 book ai didi

c - 为什么赋值时X的值不增加

转载 作者:行者123 更新时间:2023-11-30 14:39:25 24 4
gpt4 key购买 nike

我是 C 语言新手,我不完全确定为什么在第 4 行,当后增量完成时,x 的值没有改变,我的意思是这样

x = printf("%d",x++);

x 的值为 12,因此 printf 将打印 12,然后应将 x 赋值为2 并且当 ++ 存在时 x 应该稍后用 2+1 更改并在第 6 行预增量已完成,因此输出不应为 124

为什么第 4 行的 x 没有添加?

请帮忙。

#include <stdio.h>

int main(){

int x = 12;

x = printf("%d", x++);

printf("%d", ++x);

return 0;

}

最佳答案

让自己意识到序列点。来自 this [强调我的]:

There is a sequence point after the evaluation of all function arguments and of the function designator, and before the actual function call.

来自this [强调我的]:

Increment operators initiate the side-effect of adding the value 1 of appropriate type to the operand. Decrement operators initiate the side-effect of subtracting the value 1 of appropriate type from the operand. As with any other side-effects, these operations complete at or before the next sequence point.

看看这个声明:

x = printf("%d", x++);

后自增运算符将操作数的值增加1,但表达式的值是自增操作之前操作数的原始值
因此,在调用 之前,传递给 printf()x 值将是其原始值,即 12 并且由于序列点>printf() x 的值将增加 1printf() 的返回值将被分配给 x,它会覆盖 x 的最后一个值,该值是由于 post 而增加的值>++ 运算符。因此,在此语句之后,x 的值为 2

关于c - 为什么赋值时X的值不增加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56099539/

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