---
title: "Java陷阱解惑"
author: "wangym"
date: "2013-07-02T23:52:33Z"
tags: []
categories: ["编程语言"]
slug: "java"
draft: false
lastmod: "2013-11-06T21:16:25Z"
id: 1876192
url: "https://wangym.iteye.com/blog/1876192"
---

**１、自增陷阱**

陷阱：

下述程序的运行结果是多少？

```
	@Test
	public void test自增陷阱() {

		int expected = 10;

		int count = 0;
		for (int i = 0; i < expected; i++) {
			count = count++;
		}
		System.out.println(count);

		Assert.assertTrue(expected == count);
	}
```

结果是count=0不是预期的10。

 

解惑：

count++的返回值是count自增前的值。Java对自增的处理过程是：先把count的值拷贝到临时变量区，然后对count变量+1，最后返回临时变量区的值。 

```
// count = count++ 可以用下述代码来理解执行过程:
int temp = count;
count = count + 1;
return temp;
```

  

补充：

不过这个问题在不同的语言环境下会有不同的结果。比如在C++中，count=count++与count++是等效的，而在PHP中则保持着与Java相同的处理方式。