# K&R C
## 1.10 External Variable and Scope
### Definition of `automatic` variables
The variables in main, such as line, longest, etc., are **private or local** to main.
Each local variable in a function comes into existence only when the function is called, and disappears when the function is exited.
- concept of `life time`
This is why such variables are usually known as *automatic* variables, following terminology in other languages.
(Chapter 4 discusses the `static` storage class, in which local variables do retain their values between calls.)
### Definiton of 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==.
Because external variables are globally accessible, they can be used instead of argument lists to communicate data between functions.
> 函式間的資料的分享或交換,透過外部變數可以取代參數列,函式內可以直接存取該變數。
Before a function can use an external variable, the name of the variable must be made known to the function. One way to do this is to write an extern declaration in the function
> 在C99的規範前,function若要使用external variables,也必須要再宣告一次,且要加上`external` keyword.
> > 若在同一個source file,則可省略此宣告
- 範例如下:
```c
#include <stdio.h>
#define MAXLINE 1000 /* maximum input line size */
int max; /* maximum length seen so far */
char line[MAXLINE]; /* current input line */
char longest[MAXLINE]; /* longest line saved here */
...
/* print longest input line; specialized version */
main()
{
int len;
extern int max;
extern char longest[];
...
}
```
## 4.11.2 Macro Substitution
### Usages
:::success
- [ ] (TO-BE-CONCLUED) Quick note
Argument
- [of a function in `mathematics`](https://en.wikipedia.org/wiki/Argument_of_a_function)
:thinking_face: (RECALL) 函數 vs 函式
> is explained at [簡介](https://hackmd.io/@sysprog/c-function#簡介) in [你所不知道的C語言:函式呼叫篇](https://hackmd.io/@sysprog/c-function)
在 C 語言中,“function” 其實是特化的形式,並非數學意義上的函數,而隱含一個狀態到另一個狀態的關聯,因此,我們將一般的 C function 翻譯為「函式」,以區別數學意義上的函數 (如 abs, cos, exp)。
在數論,一個函數的[自變數(argument)](http://terms.naer.edu.tw/detail/2111367/)是一個值,用來提供計算此函數的結果;亦稱作獨立變數([independent variable](https://en.wikipedia.org/wiki/Dependent_and_independent_variables))。
例如:二次不定方程(the binary function) $\displaystyle f(x,y)=x^{2}+y^{2}$ 有兩個自變數,$x$和$y$, in an [ordered pair](https://en.wikipedia.org/wiki/Ordered_pair) $\displaystyle (x,y)$.
- [in `computer programming`](https://en.wikipedia.org/wiki/Parameter_(computer_programming))
:notes: called `parameter` [(參數)](http://terms.naer.edu.tw/detail/18677352/)
In [computer programming](https://en.wikipedia.org/wiki/Computer_programming "Computer programming"), a **parameter** or a **formal argument** is a special kind of [variable](https://en.wikipedia.org/wiki/Variable_(programming) "Variable (programming)") used in a [subroutine](https://en.wikipedia.org/wiki/Subroutine "Subroutine") to refer to one of the pieces of data provided as input to the subroutine.[\[a\]](https://en.wikipedia.org/wiki/Parameter_(computer_programming)#cite_note-1)[\[1\]](https://en.wikipedia.org/wiki/Parameter_(computer_programming)#cite_note-Oracle-2)
> **formal argument**: [形式引數](http://terms.naer.edu.tw/detail/18635205/)
These *pieces of data* are the values[\[2\]](https://en.wikipedia.org/wiki/Parameter_(computer_programming)#cite_note-3)[\[3\]](https://en.wikipedia.org/wiki/Parameter_(computer_programming)#cite_note-4)[\[4\]](https://en.wikipedia.org/wiki/Parameter_(computer_programming)#cite_note-5) of the **arguments** (often called _actual arguments_ or _actual parameters_) with which the subroutine is going to be called/invoked
:star: Unlike argument in usual mathematical usage, the argument in computer science is *the actual input expression passed/supplied to a function, procedure, or routine in the invocation/call statement,
- whereas the parameter is the variable inside the implementation of the subroutine*. For example,
if one defines the `add` subroutine as `def add(x, y): return x + y`, then
- `x, y` are *parameters*, while if this is called as `add(2, 3)`, then `2, 3` are *the arguments*.
- Note that *variables* (and expressions thereof) from the calling context *can be arguments*:
if the subroutine is called as `a = 2; b = 3; add(a, b)`
- then the variables a, b are the arguments, not the values 2, 3.
Substitutions are made only for tokens, and do not take place within quoted strings.
- For example, if `YES` is a defined name, there would be ++no substitution++ in ==printf("YES") or in YESMAN==.
- If, however, a parameter name is preceded by a # in the replacement text,
- the combination will be expanded into a quoted string with the parameter replaced by the actual argument.
> Translation from C語言程式設計:巨集的參數替換不會發生於引號(argument)夾住的字串,因此(Before K&R C?)"舊版的C"無法使巨集引數變成引號夾住的字串。新版規定若在替換文字中的形式參數(Formal parameters)名,由井號(`#`)帶頭,就表示該參數(actual argument)展開後要用雙引號夾住
The preprocessor operator `##`
- provides a way to ++concatenate actual arguments++ during macro expansion.
- If a parameter in the replacement text is adjacent to a ##, the parameter is replaced by the actual argument, the ## and surrounding white space are removed, and the result is rescanned
> 前處理器會把參數出現處用*實際引數*取代且將`##`號及其旁邊的*空白符號*去掉,然後重新檢視所得結果(也就是看看++是否仍有參數需替換++)
- For example, the macro paste concatenates its two arguments:
```c
#define paste(front, back) front ## back
```
- so `paste(name, 1)` creates the token `name1`.
> The rules for nested uses of ## are arcane; further details may be found in Appendix A.
:::
### Exercise 4-14.
Define a macro swap(t,x,y) that interchanges two arguments of type t. (Block structure will help.)
- [x] (Q) 如何取得paramenter`t`的*type*,來宣告一個local variable暫存x or y的值?提供以下兩種方法,以下擷取[原始碼](https://github.com/asahsieh/linux-kernel-internals/blob/main/practice/clang/macro_and_inline/KnR/exercise_4-14.c)中實作`swap(t, x, y)`的部份:
- 方法1: 直接用`t`當作*type*來宣告一個local variable
```c=19
#define swap(t, x, y) \
{ \
t _z; \
_z = y; \
y = x; \
x = _z; \
}
```
- 方法2: 使用**GNU C**提供之[extensions](https://gcc.gnu.org/onlinedocs/gcc/C-Extensions.html)的[`Typeof`](https://gcc.gnu.org/onlinedocs/gcc/Typeof.html#Typeof) operator
```c=30
#define swap(t, x, y) \
{ \
typeof(t) _z; \
...
}
```
- 上述兩種方法的輸出結果一致,如下:
```
Original values: x=10 y=5
Exchanged values: x=5 y=10
Original values: x=5 _z=15
Exchanged values: x=5 _z=15
```
> 可以看到第二次呼叫巨集`swap`沒有交換`x`與`_z`的值
:::info
:notes: 遇到了`variable shadowing`的問題,在GCC online docs中的[Statement-Exprs](https://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html)有提及此issue。
- 在wiki上的定義:[variable shadowing](https://en.wikipedia.org/wiki/Variable_shadowing)
> 當一個變數在一個特定的範疇裡宣告(如: decision block, method, or inner class), 稱作`inner variable`;但有一個相同名字的變數也在外層的範疇中宣告, 稱作`outer variable`。在不同階層的識別符(針對名字,而非變數),叫做*name masking*。
>
> outer variable如同在inner variable的陰影(*be shadowed*)底下,或叫做inner variable遮蔽(mask) outter variable
> > [shadow](https://dictionary.cambridge.org/dictionary/english-chinese-traditional/shadow?q=shadowed), verb [T] (FOLLOW), to follow closely
> > [shadow](https://www.thefreedictionary.com/shadowed) v.tr.
> > 1. To cast a shadow on; darken or shade: The leaves of the trees shadowed the ferns below.
:question: 透過identifier(name)存取該變數時,會使用到何者呢?
> 因為不清楚接下來是那一個變數被使用,故產生混淆;而決定那一個變數被使用是根據程式語言的[name resolution](https://en.wikipedia.org/wiki/Name_resolution_(programming_languages))規則。
以C++為例:
```cpp
#include <iostream>
int main()
{
int x = 42;
int sum = 0;
for (int i = 0; i < 10; i++) {
int x = i;
std::cout << "x: " << x << '\n'; // prints values of i from 0 to 9
sum += x;
}
std::cout << "sum: " << sum << '\n';
std::cout << "x: " << x << '\n'; // prints out 42
return 0;
}
```
> 於上例,inner variable是在for-loop中宣告的`x`, 當在此loop存取`x`時,scope從main切換到此loop,故會是存取inner variable (value = 0~9);而outter variable是在main() function scope裡宣告的`x` (initial value = 42), 當從loop離開時,scope又切換回main,故會是存取outter variable (value = 42)
- 回到上述程式,variable name `_z`, 被用於macro的argument及macro的內部變數;使得arguments `x`跟`_z`沒有正確做swap:
```c
#define swap(t, x, y) \
{ \
t _z; \
_z = y; \
y = x; \
x = _z; \
}
int main(int argc, char *argv[])
{
int x = 10;
int y = 5;
int _z = 15;
...
printf("Original values:\tx=%d\t_z=%d\n", x, _z);
swap(int, _z, x);
printf("Exchanged values:\tx=%d\t_z=%d\n", x, _z);
return 0;
}
```
我們在巨集中做swap操作的前後與中間插入`printf`,並用GCC `-E` option觀察preprocessor置換巨集的結果;如下:
```c
#define swap(t, x, y) \
{ \
t _z; \
printf("In swap(): Original values:\tx=%d\ty=%d\t_z=%d\n", x, y, _z); \
_z = y; \
printf("In swap(): Assign y to z:\tx=%d\ty=%d\t_z=%d\n", x, y, _z); \
y = x; \
x = _z; \
printf("In swap(): Exanged values:\tx=%d\ty=%d\t_z=%d\n", x, y, _z); \
}
```
```shell=
printf("Original values:\t\t_z=%d\tx=%d\n", _z, x);
{ int _z;
printf("In swap(): Original values:\tx=%d\ty=%d\t_z=%d\n", _z, x, _z);
_z = x;
printf("In swap(): Assign y to z:\tx=%d\ty=%d\t_z=%d\n", _z, x, _z);
x = _z;
_z = _z;
printf("In swap(): Exanged values:\tx=%d\ty=%d\t_z=%d\n", _z, x, _z); };
printf("Exchanged values:\t\t_z=%d\tx=%d\n", _z, x);
```
> 可以觀察到宣告在`main()`及巨集`swap`的變數`_z`發生了variable shadowing,而巨集有自己的scope,如同上例的loop。
---
The macros: `getchar` and `putchar`
- defined in <stdio.h>
- avoid the run-time overhead of `a function call per character processed`
Name may be undefined with `#undef`
- usually to ensure that a runtine is really a funtion, not a macro:
```c
#undef getchar
int getchar(void) { ... }
```