C语言++自增运算符优先级问题

文章目录

  • 前言
  • 一、题目:
  • 二、解决步骤
  • 1.初步分析
  • 2.上机运行验证
  • 3.逐步分析
  • 问题


前言

C运算符中,++自增运算符与其他运算符的优先级比较。
请看下面这一题。
求解决。
呃,这个提问里的ai助手一直提示:禁止重复输入同样的词汇或符号:+
代码无法上传源码,我只能上传图片了,望见谅。
我的博客主页的最新文章有关于这个问题的详细过程。


一、题目:

img

二、解决步骤

1.初步分析

这是C语言中一道考察运算符优先级的题目。初步分析如下:

img

所以结果应该是x=3,y=4

2.上机运行验证

使用Code::Blocks 20.03运行,

运行截图:

运行截图


结果出人意料,只有x=3对了。x=3,无需过多解释,不论顺序如何,x一定是自增了3次,所以一定的是等于3的。但是y=5是怎么得到的呢?

3.逐步分析

运行截图:

在这里插入图片描述

运行截图:

在这里插入图片描述

运行截图:

在这里插入图片描述

img

运行截图:

在这里插入图片描述


问题

经过这么一分析,呃,貌似属于白费力气,还是没有搞清楚原因。
望解决,本人已经思考了一下午了😭

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);

不建议这样写代码。
因为代码不具有可读性。

img


可以用Visual Studio编译工具 右键查看 进汇编看是如何执行的。
钻语法的牛角尖没有什么意义。
而且由于各编译器实现的原理不同,会导致各编译器产生不同的结果。

做这样一个测试

#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