Topic: 小心用j=j++语句 |
Print this page |
1.小心用j=j++语句 | Copy to clipboard |
Posted by: awrong Posted on: 2006-08-25 01:06 看到一个例子: int j=0; for(int i=0;i<100;i++) j=j++; System.out.println(j); 对于不同的程序语言,其运算结果会不一样,在java中运行j值为0。 对于初学java者,或者你以前学过其它程序语言的,一不小心可能会犯这样的错误。 |
2.Re:小心j=j++语句 [Re: awrong] | Copy to clipboard |
Posted by: why Posted on: 2006-08-25 01:57 I haven't seen anyone code something like j = j++ in real life. I don't think any developer would do so. |
3.Re:小心j=j++语句 [Re: awrong] | Copy to clipboard |
Posted by: ranchgirl Posted on: 2006-08-25 05:47
No matter what language you are using, you should never, ever write such garbage code!!!!!! Period! 1) In C/C++, this is undefined!!! you should not change a variable value twice in one statement. Read here http://www.research.att.com/~bs/bs_faq2.html#this 2) In Java, it is defined according to the left-to-right-evaluation rule, however, you should never, ever write such garbage code either. Read here! http://bobcat.webappcabaret.net/javachina/faq/07.htm#lef_Q2 Thanks! |
4.Re:小心j=j++语句 [Re: ranchgirl] | Copy to clipboard |
Posted by: zcjl Posted on: 2006-08-25 09:58 关心这个问题没错,不过不应该只是提出这个问题来,而应该自己尝试去了解bytecode和jvm,然后分析产生这个现象的原因 甚至,你也可以比较c/c++编译器实现原理的不同,以至于在c/c++中,这段代码的结果是不一样的 btw,这个话题在cjd已经出现得够多了,请先搜索一下 记得ranchgirl同学已经多次重申never, ever write such garbage code ^_^ |
5.Re:小心用j=j++语句 [Re: awrong] | Copy to clipboard |
Posted by: lwfllr Posted on: 2006-09-04 20:19 呃~~ 刚开始还真搞错了~~ 后来想想才发现取值>赋值后J还是0~~ 郁闷~~ |
6.Re:小心用j=j++语句 [Re: awrong] | Copy to clipboard |
Posted by: qingsure Posted on: 2006-09-04 21:18 果然,差点犯错。谢谢提醒! |
7.Re:小心用j=j++语句 [Re: awrong] | Copy to clipboard |
Posted by: leange Posted on: 2006-09-05 21:11 掌握运算先后顺序后也不会那么难理解吧?? 认真看书!! |
8.Re:小心用j=j++语句 [Re: awrong] | Copy to clipboard |
Posted by: 紫杉 Posted on: 2006-10-11 09:15 顶.讨论的不错. |
9.Re:小心用j=j++语句 [Re: awrong] | Copy to clipboard |
Posted by: cxp108 Posted on: 2006-10-12 08:45 这是一元运算符的计算顺序问题。 ++这个运算符优先顺序永远是最低的。 这个例子可能有点极端,但这个问题新手还是要多留意。 |
Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1 客服电话 18559299278 客服信箱 714923@qq.com 客服QQ 714923 |