function 是傳值的 (pass by value)

所以如果要改動某一個記憶體中的位置的話,一定要傳某變數的地址給函數,而函數的形式參數也要指定為指標類型的才行。

const 作為函數的形式參數

1
void a_function (const char *) {...}

這麼做只是為了要保護傳進來的字串(字元指標)不能被修改而已。

Generally, if you pass the value of a variable into a function (with no &), you can be assured that the function can’t modify your original variable. When you pass a pointer, you should assume that the function can and will change the variable’s value. If you want to write a function that takes a pointer argument but promises not to modify the target of the pointer, use const, like this:

1
2
3
4
5
void
printPointerTarget(const int *p)
{
printf("%d\n", *p);
}

(see link)

為什麼要傳 pointer 作為函數的參數?

Passing const pointers is mostly used when passing large structures to functions, where copying a 32-bit pointer is cheaper than copying the thing it points to. (see link)

Debugging tools

  • gdb (在OSX上是 lldb)

  • 參考資料

Automatic variable ( = local variable)

Each local variable in a function comes into existence only when the function is called, and disappears when the function is exited. This is why such variables are usually known as automatic variables, following terminology in other languages. (see K&R 2nd. 1.10)

只存活於某個函式執行時,執行完畢後,這些automatic variable就會消失。相對於此就有持存在函數之外的變數。

  • 相對的概念:
    • 在函式當中的標有 static 的 local variable,他們在多次函數的調用時保持值不變 (see K&R ch4)
    • 宣告在所有函數外部的變量,並且只能定義一次 (see External variable)
    • 關鍵字: storage class

External variable

As an alternative to automatic variables, it is possible to define variables that are external to all functions, that is, variables that can be accessed by name by any function. (This mechanism is rather like Fortran COMMON or Pascal variables declared in the outermost block.) Because external variables are globally accessible, they can be used instead of argument lists to communicate data between functions. Furthermore, because external variables remain in existence permanently, rather than appearing and disappearing as functions are called and exited, they retain their values even after the functions that set them have returned.

An external variable must be defined, exactly once, outside of any function; this sets aside storage for it. The variable must also be declared in each function that wants to access it; this states the type of the variable. The declaration may be an explicit extern statement or may be implicit from context (see K&R 2nd. 1.10)

Definition vs. Declaration

Definition'' refers to the place where the variable is created or assigned storage;declaration’’ refers to places where the nature of the variable is stated but no storage is allocated. (see K&R 2nd. 1.10)

Constant expression 常量表達式

A constant expression is an expression that involves only constants. Such expressions may be evaluated at during compilation rather than run-time. (see K&R 2nd. 2.3)

學習資源