系統程式設計學習筆記

鴨脖發表於2012-10-24

今天主要看了作用域和傳值傳引用以及遞迴,都是十分典型的問題,而且我發現卡耐基上面講的很不錯,所以做一下筆記。

首先是作用域,這裡有一個典型的程式:

#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.

意思就是每次函式呼叫之前編譯器會做一些事情,做什麼事情呢?就是插入一些額外的程式碼。這些程式碼會為函式分配區域性變數。由於程式不知道有多少區域性變數,所以全域性變數的地址和區域性變數的地址相差的很大。



相關文章