C运算符中,++自增运算符与其他运算符的优先级比较。
请看下面这一题。
求解决。
呃,这个提问里的ai助手一直提示:禁止重复输入同样的词汇或符号:+
代码无法上传源码,我只能上传图片了,望见谅。
我的博客主页的最新文章有关于这个问题的详细过程。
这是C语言中一道考察运算符优先级的题目。初步分析如下:
所以结果应该是x=3,y=4
使用Code::Blocks 20.03运行,
运行截图:
运行截图:
运行截图:
运行截图:
运行截图:
经过这么一分析,呃,貌似属于白费力气,还是没有搞清楚原因。
望解决,本人已经思考了一下午了😭
C/C++语言标准没有规定运算符的操作数的计算顺序,编译器可以按任意顺序来计算操作数的值,因此如果一个变量在同一个运算符的两个操作数分别被修改或一个修改一个读取,其结果在不同的编译器上可能不一样的。以后不要写这种代码,讨论也没有意义。
From https://en.cppreference.com/w/c/language/eval_order
Order of evaluation of the operands of any C operator, including the order of evaluation of function arguments in a function-call expression, and the order of evaluation of the subexpressions within any expression is unspecified (except where noted below). The compiler will evaluate them in any order, and may choose another order when the same expression is evaluated again.
不同的编译器处理方式不一样,以下面的例子来说明自增符号在visual studio 和devc下的不同计算过程:
例子:
int i=3;
int m=3;
int p = (i++)+(i++)+(i++);
int q = (++m)+(++m)+(++m);
不建议这样写代码。
因为代码不具有可读性。
做这样一个测试
#include <stdio.h>
int main()
{
int x=0;
int y=0;
int a = ++x;
int b = x++;
y = a+b+b;
printf("x:%d y:%d\n",x,y);
return 0;
}
输出:x:2 y:3
```c++
#include <stdio.h>
int main()
{
int x=0;
int y=0;
y = ++x + x++ + x++;
printf("x:%d y:%d\n",x,y);
return 0;
}
输出:x:3 y:5
其实y = ++x + x++ + x++;
正常的执行是
++x;此时x=1,然后1+x+x,此时,y = 3,x=3
y = ++x + x++ + x++;这条语句执行完以后再执行刚刚x++未执行完的部分,即两次自增,x=5