我想增加一个变量,所以 c 是 4,d 是 c ++ (所以是 5)
这段代码有效
#include <stdio.h>
int main()
{
int c = 4;
int d = ++c ;
printf("Value of c is: %d \n", c);
printf("Value of d is: %d \n", d);
}
Run Code Online (Sandbox Code Playgroud)
问题是 c 和 d 返回 5。
Value of c is: 5
Value of d is: 5
Run Code Online (Sandbox Code Playgroud)
我想获得这个:
Value of c is: 4
Value of d is: 5
Run Code Online (Sandbox Code Playgroud)
我的想法是声明一个var(c)将4赋值给c,然后声明d并将c++的值赋给d。bash 上有类似的东西,但使用 ++ 而不是 +1 (太简单了)
#!/bin/bash
c=4
echo "C is now $c"
d=$((++c))
echo "D is now $d"
Run Code Online (Sandbox Code Playgroud)
有什么建议吗?
如果您不想更改 的值c,则不能++对其使用运算符:
Expression Value of c Value of d
---------- ---------- ----------
d = c++ 5 4
d = ++c 5 5
d = c + 1 4 5
Run Code Online (Sandbox Code Playgroud)
和++运算--符既有结果又有副作用:
Expression Result Side effect
---------- ------ -----------
x++ Current value of x x <- x + 1
++x Current value of x + 1 x <- x + 1
x-- Current value of x x <- x - 1
--x Current value of x - 1 x <- x - 1
Run Code Online (Sandbox Code Playgroud)
运算符将修改存储在操作数中的值。