今天主要看了範圍和傳值傳引用以及遞迴,都是十分典型的問題,而且我發現卡耐基上面講的很不錯,所以做一下筆記。
首先是範圍,這裡有一個典型的程式:
#include <stdio.h>int first;int second;void callee ( int first ){ int second; second = 1; first = 2; printf("callee: first = %d second = %d\n", first, second);}int main (int argc, char *argv[]){ first = 1; second = 2; callee(first); printf("caller: first = %d second = %d\n", first, second); return 0;}
從這裡面我明白局部範圍的優先順序高於全域範圍。還有就是程式在調用函數之前會對參數做一個複製(如果是傳值的話),那麼這個局部對象怎麼才能觀察到呢?還沒解決。
另外就是傳值和傳引用。
#include <stdio.h>int first;int second;void callee ( int * first ){ int second; second = 1; *first = 2; printf("callee: first = %d second = %d\n", *first, second);}int main (int argc, char *argv[]){ first = 1; second = 2; callee(&first); printf("caller: first = %d second = %d\n", first, second); return 0;} |
這個程式只是傳指標,其實還是傳值,因為指標的值是通過傳值傳進去的。其實傳引用只是改變了一下形勢,傳指標和傳引用是等價的。
標準的傳值
void fun(int a);
標準的傳引用
void fun(int& a);
#include <stdio.h>#include <stdlib.h>void callee (int n){ if (n == 0) return; printf("%d (0x%08x)\n", n, &n); callee (n - 1); printf("%d (0x%08x)\n", n, &n);}int main (int argc, char * argv[]){ int n; if (argc < 2) { printf("USAGE: %s <integer>\n", argv[0]); return 1; } n = atoi(argv[1]); callee(n); return 0;} |
下面這段話講的很好:
What happens is that the compiler inserts additional code for every function call and every function return. This code allocates any local variables that the callee needs for that invocation. Multiple invocations
of the callee activate this allocation code over and over again. This is called dynamic allocation, because the local variables are allocated at runtime, as needed.
Global variables can be allocated statically. This means that the compiler can fix specific addresses for global variables before the program executes. But because functions can be called recursively, and
each recursive invocation needs its own instantiation of local variables, compilers must allocate local variables dynamically. Such dynamic behavior makes the program run more slowly, so it is not desirable. But it is necessary for local variables.
意思就是每次函數調用之前編譯器會做一些事情,做什麼事情呢?就是插入一些額外的代碼。這些代碼會為函數分配局部變數。由於程式不知道有多少局部變數,所以全域變數的地址和局部變數的地址相差的很大。