在C和Java preIncrement和后运营商的行为 [英] Behaviour of PreIncrement and PostIncrement operator in C and Java

查看:117
本文介绍了在C和Java preIncrement和后运营商的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我跑在Visual C以下为节目++和Java:

I'm running the following programs in Visual C++ and Java:

的Visual C ++

void main()
{
    int i = 1, j;
    j = i++ + i++ + ++i;
    printf("%d\n",j);
}

输出:

6

Java的:

public class Increment {
    public static void main(String[] args) {
        int i = 1, j;
        j = i++ + i++ + ++i;
        System.out.println(j);
    }
}

输出:

7

为什么这两种语言的输出有什么不同?无论是汉语语言如何看待pre和后运营商不同?

Why the output in these two languages are different? How both the langauges treat pre and postincrement operators differently?

推荐答案

在C / C ++的行为是不确定的,因为在这个前pression I 修改更多的则一旦没有插入顺序点。阅读:什么是我的价值++ + i ++在

In C/C++ behavior is undefined because In this expression i is modified more then once without an intervening sequence point. read: What's the value of i++ + i++?

中,当然在这种codeS 是很好的界定。
下面是我的回答对Java,一步一步:

Of-course in Java behaviour of this kind of codes is well defined. Below is my answer for Java, step by step:

起初 I 1

j = i++ + i++ + ++i;
// first step, post increment
j = i++ + i++ + ++i;
//  ^^^
j = 1   + i++ + ++i;
// now, i is 2, and another post increment:
j = i++ + i++ + ++i;
//  ^^^^^^^^^
j = 1   + 2   + ++i;
// now, i is 3 and we have a pre increment:
j = i++ + i++ + ++i;
//  ^^^^^^^^^^^^^^^^
j = 1   + 2   +   4;
j = 7;

这篇关于在C和Java preIncrement和后运营商的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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