Kyle Hsieh (謝阿Sa)
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # 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) { ... } ```

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully