Re: [問題] 為什麼local variable的scope不能延及ꐠ…

看板PLT (程式語言與理論)作者 ( )時間17年前 (2008/03/06 22:30), 編輯推噓1(103)
留言4則, 2人參與, 最新討論串9/9 (看更多)
無聊沒事, 再來回一篇... ※ 引述《zerodevil (冰心無情)》之銘言: : 其實如果允許nested function的話 : 拿到上一層function的變數也沒什麼不好 : : function foo() { : var x = 1; : function bar() {alert(x)} : bar(); : } : 我想應該不用特別解釋了 : 這個例子的bar可以看到x然後印出1 : : bar宣告在foo裡面, : 所以bar在的時候一定有x可以用 : 想在compile time算出x的address也不是什麼問題 是的, Pascal 就是如此 只是如果是用到好幾層外的變數有可能要查好幾次 base address 就是了 其實 gcc 也可以... $ cat t.c #include <stdio.h> int main(){ int x = 1; int a(){ int b(){ x = 2; } b(); } a(); printf("%d\n", x); return 0; } $ gcc t.c $ ./a.out 2 : (如果javascript可以compile的話) : : 這樣godfat大提到的問題或許可以少一些? : : -- : ※ 發信站: 批踢踢實業坊(ptt.cc) : ◆ From: 140.112.90.68 : ※ 編輯: zerodevil 來自: 140.112.90.68 (03/06 04:21) : 推 linjack:這應該是比較像 lambda / closure 的概念?不太一樣吧._.? 03/06 11:40 : 推 godfat:同意 linjack, 這樣是無法無中生上層的 local var 的 03/06 15:11 : → godfat:也就是那有一定的限制在,不能任意操作 local var 03/06 15:12 其實 gcc 的實作和 Pascal 是類似的 (我沒細看 gcc -S 的結果, 但是複雜的程度有點像) 而他們有個共通點: 不支援 returning local function $ cat t.c #include <stdio.h> int (*a())(); int c(); int main(){ int (*f)(); int x = 1; f = a(); c(); x = f(); printf("%d\n", x); return 0; } int (*a())(){ volatile int x = 2; int b(){ return x; } return &b; } int c(){ volatile int y = 3; volatile int z = y + 1; volatile int w = z + 1; return w; } $ gcc t.c $ ./a.out 5 如果在 c() 裡再加個 volatile int v = w + 1; 甚至會 segmentation fault 但是 javascript, perl 之類的語言都可以做到 這才是 linjack 所說的 closure 大部份的 functional language 也都支援, 而且是 functional programming 時一個重要的工具.. 繞回原題... lisp 從 dynamic scoping 換到 static scoping 時, 因為很多變數忽然「拿不到了」 於是 closure 成了「又拿得到了」的方法 XD -- All this will not be finished in the first 100 days. Nor will it be finished in the first 1,000 days, nor in the life of this Administration, nor even perhaps in our lifetime on this planet. But let us begin. -- John F. Kennedy, Inaugural Address -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.112.30.54

03/06 22:47, , 1F
gcc 居然有這種 ext @@ 第二段那些看不太懂... 大概是在弄
03/06 22:47, 1F

03/06 22:47, , 2F
call stack 的東西?所以才需要 volatile, 猜的
03/06 22:47, 2F

03/06 22:55, , 3F
嗯, 因為不確定會不會被 optimize 掉, 所以加 volatile
03/06 22:55, 3F

03/06 22:55, , 4F
強制 override memory
03/06 22:55, 4F
文章代碼(AID): #17p__t9l (PLT)
討論串 (同標題文章)
文章代碼(AID): #17p__t9l (PLT)