c中的递增和递减操作 [英] increment and decrement operation in c

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

问题描述

#include<stdio.h>
#include<math.h>
int main()
{
    int a=2,b;
    b=a++ + a-- + ++a + --a;
    printf("%d %d",a,b);
}









输出是2 9为什么? ????





output is 2 9 why?????

推荐答案

啊,我期待你的最后一张......



预增量运算符和+运算符具有相同的优先级。这意味着首先完成哪一个完全依赖于编译器。这称为未定义行为,应不惜一切代价避免这些类型的语句。



为什么会在编译器中发生?它只是编译器决定应用+和++ / - 前缀运算符的优先级。我没有通过你的等式,但它可以先加法,或先减法。



最近有一个关于这个的热烈讨论此处 [ ^ ],阅读线程以查看所说的内容,并忽略那个没有得到它的人:)
Ahh, I expected this one from your last one...

The pre-increment operator and the + operators have equal precedence. That means which one is done first is completely compiler dependent. This is called undefined behavior and these types of statements should be avoided at all costs.

Why does it happen in your compiler? Its simply the precedence that the compiler decided to apply the + and ++/-- prefix operators in. I didn't work through your equation but it can either do the addition first, or the subtraction first.

There has recently been a lively discussion on this here[^], read the thread to see what is said, and ignore the guy who doesn't get it :)


第一个结果(2)非常明显,因为 a 增加两次并递减两次。因此 a 之后的价值与以前相同。



第二个结果(9)就是那个不那么容易看到。 b 的值取决于编译器选择执行后递增和后递减操作的时间。整个表达式完成后,您的编译器已选择它们。因此b计算如下:

The first result (2) is pretty obvious, because a is incremented two times and decremented two times. Hence a has afterwards the same value as before.

The second result (9) is the one that is not so easy to see. The value of b depends on the time when the compiler chooses to do the post-increment and post-decrement operations. Your compiler has chosen to them after the entire expression has been completed. Hence b is computed as:
b = 2 + 2 + 3 + 2;
    // afterwards the post-increment and post-decrement operators
    // are performed



注意通过预增量和预减量运算,编译器别无选择,只能立即执行。因此最后两个值是3和2.



正如Ron在解决方案1中正确指出的那样,这个表达式的结果实际上是未定义的。编译器可能选择在较早的时间执行后增量和后减量操作,这可能导致:


Note that with pre-increment and pre-decrement operations the compiler has no other choice than doing them right away. Hence the last two values are 3 and 2.

As Ron has correctly pointed out in solution 1, the result of this expression is actually undefined. The compiler could have chosen to perform the post-increment and post-decrement operations at an earlier time and that could have resulted in:

b = 2 + 3 + 3 + 2; // == 10



写这样的语句当然不是一个好主意。这里的例子有点构造,只是为了证明如果滥用后递增/递减运算符,可以发生什么。


int a = 2,b;

b = a ++ + a-- + ++ a + --a;

1.b = a ++ // 2

2.b = a-- // 2

3.b = ++ a // 3

4.b = - a // 2



b = a ++ + a-- + ++ a + --a; // 9
int a=2,b;
b=a++ + a-- + ++a + --a;
1.b=a++ //2
2.b=a-- //2
3.b=++a //3
4.b=--a //2

b=a++ + a-- + ++a + --a;//9


这篇关于c中的递增和递减操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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