【问题标题】:why same code in two technology behaving different [duplicate]为什么两种技术中的相同代码表现不同[重复]
【发布时间】:2013-08-02 07:34:31
【问题描述】:

下面是我的 C 代码 sn-p。

void main(){
 int x = 7;
 x = x++;
 printf("%d",x);
}

输出:8

public static void main(String[] args){

        int x = 7;

        x =  x++;
        System.out.println(x);
    }

输出:7

我不明白为什么两种语言都给出不同的输出。 我在下面提到了链接 What is x after "x = x++"?

【问题讨论】:

标签: java c post-increment


【解决方案1】:

在x++之后的java中x的值没有变化

x = x++;等于

int i= x;
x = x + 1;
x = i;

所以xi

保持相同

您可以从这里阅读更多内容:Why are these constructs (using ++) undefined behavior?

【讨论】:

  • 为什么这等价于 int i= x; x = x + 1; x = 我;在 java 中不是在 C 中
  • @RohitKumar 请通过随附的链接。
【解决方案2】:

在第二个示例中,赋值首先保存 x 的值,然后将 x 设置为其值加 1,并且, 最后,将 x 重置为其原始值。 种类:

int temp=x;
x=x+1;
x=temp;

【讨论】:

    【解决方案3】:
    x=x++;
    

    这会在 C 中给出任意结果,主要取决于编译器。阅读 C 中的 sequential points。您可以通过 Dennis ritchie 引用 C Programming

    【讨论】:

      猜你喜欢
      • 2019-08-14
      • 2022-12-05
      • 2019-04-09
      • 1970-01-01
      • 2015-03-07
      • 1970-01-01
      • 2018-03-07
      • 1970-01-01
      • 2016-05-12
      相关资源
      最近更新 更多