注册 登录
编程论坛 C++教室

c++新人,小白问题

SDLXH 发布于 2018-12-03 10:52, 2045 次点击
在C++中,++或--是什么意思,求大神解答一下
7 回复
#2
乌木2018-12-03 10:53
自加和自减
++使操作数按其类型增加一个单位,--相反

[此贴子已经被作者于2018-12-3 10:55编辑过]

#3
SDLXH2018-12-03 11:08
那放在前面与后面效果是一样的吗
#4
SDLXH2018-12-03 11:15
回复 2楼 乌木
那放在前面与后面效果是一样的吗
#5
乌木2018-12-03 11:18
不一样的。
例如:
1.前置自增
++a;//相当于a=a+1
a=5;//赋值
b=++a;//a先加一并改变,然后赋给b,此时b==a==6
2.后置自增
a++;//相当于a=a+1
a=5;//赋值
b=a++;//a的值先赋给b,然后a加一,此时b==5,a==6
总的来说就是优先级的问题。
#6
rjsp2018-12-03 12:15
参见:https://zh.

++x
副作用:x自增一
表达式评估:x增一后的引用

x++
副作用:x自增一
表达式评估:x增一前的值副本

题主应当看官方或准官方的标准规定,做到 不听谣, 不信谣, 不传谣
8.2.6 Increment and decrement
The value of a postfix ++ expression is the value of its operand. [ Note: The value obtained is a copy of the original value — end note ] The operand shall be a modifiable lvalue. The type of the operand shall be an arithmetic type other than cv bool, or a pointer to a complete object type. The value of the operand object is modified by adding 1 to it. The value computation of the ++ expression is sequenced before the modification of the operand object. With respect to an indeterminately-sequenced function call, the operation of postfix ++ is a single evaluation. [ Note: Therefore, a function call shall not intervene between the lvalue-to-rvalue conversion and the side effect associated with any single postfix ++ operator. — end note ] The result is a prvalue. The type of the result is the cv-unqualified version of the type of the operand. If the operand is a bit-field that cannot represent the incremented value, the resulting value of the bit-field is implementation-defined.

8.3.2 Increment and decrement [expr.pre.incr]
The operand of prefix ++ is modified by adding 1. The operand shall be a modifiable lvalue. The type of the operand shall be an arithmetic type other than cv bool, or a pointer to a completely-defined object type. The result is the updated operand; it is an lvalue, and it is a bit-field if the operand is a bit-field. The expression ++x is equivalent to x+=1.



[此贴子已经被作者于2018-12-5 09:07编辑过]

#7
疏影黄昏2018-12-04 19:08
a++就是先使用后自增1,++a就是先自增1再使用,但其实两者仅仅在用于表达式中时会有这个差别。如果作为一个单独的变量,就没有差别。比如 int a=0;a++;int b=a+1;此时b的值就是2。但是如果是int a=0;int b=a++ +1;这个情况下b的值是1。对应的int a=0;++a;int b=a+1;的值是2。但是如果是int a=0;int b=++a +1;这个情况下b的值还是2。这就体现出++a和a++的差别了...,另外所谓C++的意思据传就是比C增加了那么一点点东西,C#原来叫J++,意思就是比Java多了那么一点点东西,不过后来好像被告了。
#8
疏影黄昏2018-12-04 19:21
这里int a=0;int b=a++ +1;分解开来看就是:
 int a=0;
 int b=a+1;//b的值这一步直接求出了
 a=a+1;
对应的int a=0;int b=++a+1;分解的下来就是:
 int a=0;
 a=a+1;
 int b=a+1;//b的值在最后求出
a--/--a道理是一样的,不知道你有没有看懂?不过一般来说,编程时不会使用这种具有迷惑性的表述,怎么简单怎么来是坠吼的。
辅助理解下:
我为什么说作为变量没有影响?请看:
如果有代码:
int a=0;
a++;
cout<<a;
此时结果和下面代码:
int a=0;
++a;
cout<<a;其实是一样的,都是自增1,其值就是1。这里没有运算的顺序要求,如果cout<<a++/cout<<++a的话就不同了
希望能帮到你吧
1