在C和Java逻辑的差异 [英] Logic differences in C and Java

查看:116
本文介绍了在C和Java逻辑的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编译并运行在C中,它code

Compile and run this code in C

#include <stdio.h>

int main()
{
  int a[] = {10, 20, 30, 40, 50};
  int index = 2;
  int i;

  a[index++] = index = index + 2;
  for(i = 0; i <= 4; i++)
    printf("%d\n", a[i]);
}

输出: 10 20 4 40 50

现在在Java同样的逻辑

Now for the same logic in Java

class Check
{

  public static void main(String[] ar)
  {
    int a[] = {10, 20, 30, 40, 50};
    int index = 2;

    a[index++] = index = index + 2;
    for(int i = 0; i <= 4; i++)
      System.out.println(a[i]);
  }
}

输出: 10 20 10 41 50

为什么会出现两种语言输出差,输出是可以理解的的Java ,但我无法理解在 C的输出

Why is there output difference in both languages, output is understandable for Java but I cannot understand output in C

还有一件事,如果我们应用preFIX ++ 运营商,我们得到了相同的结果在两种语言,为什么?

One more thing, if we apply the prefix ++ operator, we get the same result in both languages, why?

推荐答案

这是因为 A [指数++] =指数=指数+ 2; 调用在C未定义行为
看看

That is because a[index++] = index = index + 2; invokes Undefined Behavior in C. Have a look at this

从链接:

..第二句话说:如果对象是一个完整的前pression中写到,任何和所有访问它同前pression必须直接参与的价值来计算内被写入。此规则有效地限制了法律前pressions到那些其中访问demonstrably precede修改。例如,旧的备用I = I + 1是允许的,因为我的访问被用于确定我的最终值。这个例子

..the second sentence says: if an object is written to within a full expression, any and all accesses to it within the same expression must be directly involved in the computation of the value to be written. This rule effectively constrains legal expressions to those in which the accesses demonstrably precede the modification. For example, the old standby i = i + 1 is allowed, because the access of i is used to determine i's final value. The example

 a[i] = i++


  
  

是不允许的,因为我的访问之一( 一中[I])无关,与存储在我(发生过在我++),它最终的价值,所以有没有什么好的办法来定义 - 无论是对我们的理解或compiler's - 访问是否应该之前或增加值存储在举行。因为没有界定它没有什么好办法,标准声明它是未定义的,而且移植的程序根本不能使用这样的结构。
  类似 A [I +] =我(调用UB)你的前pression太调用UB。

is disallowed because one of the accesses of i (the one in a[i]) has nothing to do with the value which ends up being stored in i (which happens over in i++), and so there's no good way to define--either for our understanding or the compiler's--whether the access should take place before or after the incremented value is stored. Since there's no good way to define it, the Standard declares that it is undefined, and that portable programs simply must not use such constructs. Similar to a[i++]=i (which invokes UB) your expression too invokes UB.

您的前pression也有类似的行为。

Your expression also has a similar behavior.

该行为是井 Java定义的

这篇关于在C和Java逻辑的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆