[問題] compiler預先指定變數

看板C_and_CPP (C/C++)作者 (eleghost)時間16年前 (2009/12/10 23:15), 編輯推噓2(203)
留言5則, 2人參與, 最新討論串1/1
遇到的問題: (題意請描述清楚) 今天想到一個問題... struct _table { int a; char *b; int c; }; struct _table init_table = { 0, "aaa", 1}; 我可以用上面的方式當作初始化struct的方式。 但是如果是這樣.. struct _table init_table = { param.hHeight, "aaA", param.hWidth}; 這樣子雖然編譯會過, 但是結果卻不是如你所想的... 因為這些值是在compiler時就指定的了, 那因為param.xxx的值是在 runtime才指定的, 所以上面那樣的初始方式是錯的~ 可是我們也常常在初始化時會寫 int width = param.hHeight; 這樣, 但是這樣子結果就是如你所想的...為什麼有時候 compiler會幫你在編一階段就決定,有時卻會留在 runtime 時在決定呢? 謝謝! 開發平台: (例: VC++ or gcc/g++ or Dev-C++, Windows or Linux) linux ; gcc4 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 59.127.201.105

12/10 23:21, , 1F
int width = param.hHeight; // width的賦值也是runtime
12/10 23:21, 1F

12/10 23:21, , 2F
才給的啊....@_@"
12/10 23:21, 2F
所以 struct _table init_table = { param.hHeight, "aaA", param.hWidth}; 想上面這樣子的寫法, init_table也可以正確的被賦予初始值囉? 因為我本來是這樣寫, 但同事是說這樣會錯誤~ 所以想問問... ※ 編輯: eleghost 來自: 59.127.201.105 (12/11 22:51)

12/12 17:17, , 3F
你這東西必須在param比他先初始化的前提
12/12 17:17, 3F

12/12 17:18, , 4F
全域變數的初始化 除非param是read-only,否則你不能確定
12/12 17:18, 4F

12/12 17:19, , 5F
初始化順序。不然就是struct _table必須是區域變數
12/12 17:19, 5F
文章代碼(AID): #1B8H2Tjw (C_and_CPP)
文章代碼(AID): #1B8H2Tjw (C_and_CPP)