code.club

 找回密碼
 立即註冊
搜索
查看: 6642|回復: 2
打印 上一主題 下一主題

C語言的遞增和遞減運算規則問題

[複製鏈接]
跳轉到指定樓層
樓主
發表於 2014-8-25 21:26:16 | 只看該作者 回帖獎勵 |倒序瀏覽 |閱讀模式
本帖最後由 return 於 2014-8-25 21:37 編輯

有關x++和x--,書上都只提了如果x=1,y=x++,則y=1 x=2這樣簡單的規則。
但如果多幾次類似的運算呢?有何規則嗎?


用比較單純的例子來看似乎可以找到規則,如下二例:

#include <stdio.h>

int main(void){

int x=1;
printf("%d %d %d %d %d",x,x++,x++,x++,x++);
return 0;
}

答案是 5 4 3 2 1

#include <stdio.h>

int main(void){

int x=9;
printf("%d %d %d %d %d",x,x--,x--,x--,x--);
return 0;
}

結果則是 5 6 7 8 9


從以上二個答案來看,似乎可以得到一個規則就是說這些計算是從後面往前的。但再看以下的一些例子,似乎又不完全符合這規則?

#include <stdio.h>

int main(void){

int x=1;
printf("%d %d %d %d %d",x++,x--,x++,x,x--);
return 0;
}

答案是 0 1 0 1 1 (我以為應該是 0 1 0 0 1)


#include <stdio.h>

int main(void){

int x=1;
printf("%d %d %d %d %d",x++,x--,x++,x--,x);
return 0;
}

答案也是 0 1 0 1 1(本例符合由後往前算的結果)

#include <stdio.h>

int main(void){

int x=1;
printf("%d %d %d %d",x++,x--,x++,x);
return 0;
}

答案是 1 2 1 2(我以為應該是 1 2 1 1)



有先進能解答一下如上面這些例子++ or --的規則嗎?

thanks!!
回復

使用道具 舉報

沙發
 樓主| 發表於 2014-8-26 14:05:12 | 只看該作者
看了一下網路上的類似討論,似乎這是C語言和C++語言會有的所謂 undefined behavior,未定義的行為。
相關討論和文章:
http://blog.ez2learn.com/2008/09/27/evil-undefined-behavior/
http://www.programmer-club.com.tw/ShowSameTitleN/c/32741.html
http://c-faq.com/expr/index.html
回復 支持 反對

使用道具 舉報

板凳
 樓主| 發表於 2014-8-27 21:53:21 | 只看該作者
在標準中,有三種行為方式的規定:

一:unspecified behavior,未指定行為。意思是標準提出兩種或多種處理方法,編譯器可以從中選擇一種;

二:implemantation defined,實現定義行為。基本意思跟unspecified一樣,也是編譯器從中選擇一種,但是,編譯器需要在說明文檔中指出此編譯器採用了哪一種方法,而unspecified不需要告訴使用者。

三:就是undefined behavior了,未定義行為。意思是標準對於此施加於錯誤的程序結構或者錯誤數據上的行為,不作任何規定。編譯器可以自行處理。
回復 支持 反對

使用道具 舉報

您需要登錄後才可以回帖 登錄 | 立即註冊

本版積分規則

小黑屋|手機版|Archiver|code.club  

GMT+8, 2024-4-26 08:34 , Processed in 0.096598 second(s), 18 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回復 返回頂部 返回列表