C增加和减少输出问题 [英] C increment and decrement output problems

查看:76
本文介绍了C增加和减少输出问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

第一个printf输出是11,11。第二个输出是10,20为什么20个不应该是21?

First printf output is 11, 11. Second one is 10, 20 why is it 20 shouldn't it be 21?

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int a=10,b=++a;
    printf("%d,%d\n",a,b);
    b=a+--a;
    printf("%d,%d",a,b);
}





我的尝试:



我真的不明白它是如何工作的。



What I have tried:

I really don't understand how it works.

推荐答案

这与序列点有关。我相信20和21都是有效的答案,因为编译器可以自由选择何时评估 - a ,所以它可以递减 a 添加之前或之后。您唯一知道的是,在分配到 b 之后, a 将具有值20.

您应该避免在不同位置同时访问和使用同一变量的递增/递减运算符的表达式。这包括将变量传递给函数。例如
This has to do with sequence points. I believe that both 20 and 21 are valid answers, since the compiler is free to choose when to evaluate --a, so it can either decrement a before or after the addition. The only thing you know for sure is that following the assignment to b, a will have the value 20.
You should avoid expressions that access and use the increment/decrement operators on the same variable at the same time in different locations. This includes passing the variable to functions. For example
int a=10;
printf("%d, %d\n", a, --a)

可能会打印10,9,或者它可能会打印9,9

might print "10, 9", or it might print "9, 9"


它之前会执行前缀操作符( - )还有别的。


当a是11时b $ b,那么



b = a +( - a)

= 10 + 10



a更新为inline;没有中间存储。
It'll do the "prefix" operator (--) before anything else.

when a is 11, then

b=a+(--a)
= 10 + 10

a is updated "inline"; there is no intermediate storage.


引用:

我真的不明白它是如何工作的。

I really don't understand how it works.



这是一个灰色区域。

AC编译器可以按照它认为适合代码的方式自由重写代码。

所以不同的编译器会得到不同的结果,所有都是正确的,它是不可预测的,而且大部分时间都是意外的。

安全规则是永远不要使用多次改变的变量在一行代码中。


This is a gray zone.
A C compiler is free to rewrite your code the way it sees fit inside a line of code.
So different compiler will get different result and all are correct, it is unpredictable, and most of the time, unexpected.
The rule of safety is to never use more than once a variable that get changed in a line of code.


这篇关于C增加和减少输出问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆