前后增量/减量输出 [英] Pre and post increments/decrements output

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

问题描述

Hello guys i am new to c language. The output of the following is 6264 but i can't figure out how they got that. Please explain it. 





void main()

{

int a,b;

a = b = 4;

b = a ++;

printf(%d%d%d%d,a ++, - b, ++ a,b--);

getch();

}



什么我试过了:



i已经尝试了youtube和其他一些论坛,但我无法得到明确答案。



void main()
{
int a,b;
a=b=4;
b=a++;
printf("%d%d%d%d",a++,--b,++a,b--);
getch();
}

What I have tried:

i have tried youtube and some other forums but am unable to get a clear answer.

推荐答案

因为那个输出不是六千二百六十四。它只是六二六四。但是,当我在线运行相同的程序时( C ++ Shell [ ^ ]),我得到以下输出,



Because that output is not six thousand, two hundred and sixty four. It is only "six two six 4". However, when I run the same program online (C++ Shell[^]), I get the following output,

// Example program
#include <stdio.h>
#include <string>

int main()
{
    int a,b;
    a=b=4;
    b=a++;
    printf("%d%d%d%d",a++,--b,++a,b--);
}
// 6274



会发生变量值递增或递减的情况。 a ++表示a = a + 1,类似地表示 - 。这里的区别或主要内容是运算符的前缀和后缀。在前缀中,表达式(完整表达式)在使用当前表达式和更新值之前得到解析,但在另一种情况下(后缀),使用旧值解析当前表达式,然后递增值/递减。



在你的代码中,只有


What happens is that the variable values are incremented or decremented. "a++" means "a = a + 1" and similarly for "--". The difference, or the main thing to understand here is, the prefix and postfix of the operators. In a prefix, the expression (the full expression) gets resolved before the current expression and the updated value is used, however in the other case (postfix), the current expression is resolved using the old value, and then the value is incremented/decremented.

In your code, only

b = a++;
// Here b = 4, but after this line a = 5



这是诡计的行,否则其余的应该没问题。



我建议你在再试一次之前阅读它们, c - 前缀和后缀运算符之间有什么区别? - 堆栈溢出 [ ^ ]

Postfix增量和减量运算符:++和 - [ ^ ]


您处于灰色区域。允许C编译器重写你的代码。

只要在一行代码中,你多次使用一个变量并加上一些递增/递减,代码就是不可预测的。这取决于编译器的内部结构。

与人们的想法相反,

You are in gray zone. The C compiler is allowed to rewrite your code.
As soon as in a line of code, you use a variable more than once combined with some increment/decrement, the code is unpredictable. It depend on the compiler internals.
Contrary to what one can think,
printf("%d%d%d%d",a++,--b,++a,b--);



是不可预测的,这取决于编译器的内部结构。



相反


is unpredictable, It depend on the compiler internals.
Contrary to

printf("%d%d",a++,--b);
printf("%d%d",++a,b--);



是可预测的。


which is predictable.


这篇关于前后增量/减量输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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