增量和减量运算符 [英] Increment and Decrement Operators
问题描述
#include <stdio.h>
int main()
{
int x = 4, y, z;
y = --x;
z = x--;
printf("%d %d %d", x, y, z);
}
输出:2 3 3
有人可以解释吗?
i =+ j
是什么意思(假设i = 1
和j = 2
)?
简单说明:
-x或++ x :之后将修改值.
x--或x ++ :值将在之前修改
详细说明:
-x或++ x :预减量/增量:首先将进行减量或增量操作,然后将x赋值.>
x--或x ++ : post:减量/增量:将首先分配x的值,然后再进行减量或增量操作.
让我们以更好的格式编写代码,并逐步检查代码并对其进行注释,以直观地向您展示发生的情况:
main() {
//We declare the variables x, y and z, only x is given a value of 4.
int x=4,y,z;
//--x will decrement var x by 1 first THEN it will assign the value of x to y.
//so: x = 3, y = 3 and z = nothing yet.
y = --x;
//x-- will assign the value of x to z first, then var x will be decremented by 1 after.
//so: x = 2, y=3 and z = 3
z = x--;
printf ("\n %d %d %d", x,y,z);
}
#include <stdio.h>
int main()
{
int x = 4, y, z;
y = --x;
z = x--;
printf("%d %d %d", x, y, z);
}
Output: 2 3 3
Can anyone explain this?
And what does i =+ j
mean (suppose i = 1
and j = 2
)?
simple explanation:
--x or ++x : Value will be modified after.
x-- or x++ : Value will be modified before
Detailed explanation:
--x or ++x: pre-decrement/increment: will first do the operation of decrementing or incrementing first, then it will assign x.
x-- or x++: post:decrement/increment: will first assign the value of x and then it will do the operation of decrementing or incrementing after.
lets write your code in a nicer format and go through your code step by step and annotate it to show you visually what happens:
main() {
//We declare the variables x, y and z, only x is given a value of 4.
int x=4,y,z;
//--x will decrement var x by 1 first THEN it will assign the value of x to y.
//so: x = 3, y = 3 and z = nothing yet.
y = --x;
//x-- will assign the value of x to z first, then var x will be decremented by 1 after.
//so: x = 2, y=3 and z = 3
z = x--;
printf ("\n %d %d %d", x,y,z);
}
这篇关于增量和减量运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!