# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
This site has an agentic ask interface you may use to query the documentation dynamically by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://beej-c-zhtw.netdpi.net/index.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

---

# 簡介

本書是 C 語言的教學，有許多實際的範例可供參考。

* 譯者：[Aaron Liao (廖明沂)](https://www.linkedin.com/in/aaron-liao-bb50b6147/)
* 更新：2022 起
*


# 原著資訊

書名：Beej’s Guide to C Programming

作者：Brian “Beej Jorgensen” Hall

版次：Version 0.9.5, 2022.

網站：​<https://beej.us/guide/bgc/>

PDF:

{% file src="/files/oC8G4IhAy638YOC8I1DP" %}


# 中文翻譯日誌

這本書的中文化預計採用敏捷方式進行翻譯，現在並非完整的中譯版本，如果您有興趣，歡迎加入。

* 2022 啟動翻譯計畫，牛步進行中。


# 聯絡譯者

對於中文翻譯的詞句有任何建議，如語意不夠貼切等或輸入的文字錯誤，都歡迎來信告知譯者，幫忙提升中文譯本的品質，謝謝。

* Aaron Liao
* Web: <http://aaron.netdpi.net>
* Email: <aaron@netdpi.net>

此書最新版本目前放置於 Gitbook：<https://beej-c-zhtw.netdpi.net>


# 1. 作者序

廢話不多說，我們直接看程式碼吧。

{% code lineNumbers="true" %}

```c
E((ck?main((z?(stat(M,&t)?P+=a+'{'?0:3:
execv(M,k),a=G,i=P,y=G&255,
sprintf(Q,y/'@'-3?A(*L(V(%d+%d)+%d,0)
```

{% endcode %}

公主與王子他們從此過著幸福快樂的日子，劇終。

蛤，什麼？你說還沒把整個 C 語言程式設計給說清楚嗎？

好啦，老實說，我也不太確定上面那個程式碼範例可以做什麼。程式碼的來源是在 2001年的 [International Obfuscated C Code Contest](https://www.ioccc.org/)[1 ](https://beej.us/guide/bgc/html/split/footnotes.html#fn1)其中一段程式碼，有個很厲害的參賽者試著寫出非常不可讀的 C 程式碼，但結果往往是出人意料的。

壞消息是如果你是個完全的初學者，那麼全部的 C 程式碼對你而言可能都是霧裡看花。不過好消息是，不用擔心，這個狀況很快就會改善了！

我們在這裡會努力將您從完全不懂、完全感到困惑的情況，引導到純 C 語言程式設計才能帶給你的幸福感。


# 1.8. 著作權與散佈

Beej's Guide to C 著作權所有© 2021 Brian "Beej Jorgensen" Hall。

除了以下原始程式碼與翻譯的特定例外情況，此作品系依據 Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 授權進行授權。若要檢視此授權的復本，請造訪<https://creativecommons.org/licenses/by-nc-nd/3.0/> 或傳送信函至Creative Commons，171 Second Street, Suite 300, San Francisco, California, 94105, USA。

許可的「無衍生作品」部分的一個特定例外情況如下：本指南可以自由翻譯成任何語言，前提是翻譯正確，而且必須是完整複印。對翻譯的授權限制與對原文指南的限制相同。翻譯中可能還包括翻譯人員的姓名和聯絡資料。 本檔案所提供的C原始程式碼已授權給公用領域，且完全不受任何授許可限制。教育工作者可以自由地向學生推薦或提供本指南的副本。如需詳細資訊，請連絡 <beej@beej.us>。

下列是英文版權

Beej’s Guide to C is Copyright © 2021 Brian “Beej Jorgensen” Hall.

With specific exceptions for source code and translations, below, this work is licensed under the Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 License. To view a copy of this license, visit [`https://creativecommons.org/licenses/by-nc-nd/3.0/`](https://creativecommons.org/licenses/by-nc-nd/3.0/) or send a letter to Creative Commons, 171 Second Street, Suite 300, San Francisco, California, 94105, USA.

One specific exception to the “No Derivative Works” portion of the license is as follows: this guide may be freely translated into any language, provided the translation is accurate, and the guide is reprinted in its entirety. The same license restrictions apply to the translation as to the original guide. The translation may also include the name and contact information for the translator.

The C source code presented in this document is hereby granted to the public domain, and is completely free of any license restriction.

Educators are freely encouraged to recommend or supply copies of this guide to their students.

Contact [`beej@beej.us`](https://beej.us/guide/bgc/html/split/beej@beej.us) for more information.


# 3. 變數與陳述式

```
「要創造世界需要各種各樣的東西，不是嗎，神父？」 
「我兒子就是這樣，就是這樣。」
—Pirate Captain Thomas Bartholomew Red to the Padre, Pirates
```

C 語言一定有很多好的素材。

是啊。

由於各種原因，如果我們把程式中可以找到的一些型別進行分類的話，大家都會比較容易清楚地知道我們在說些什麼。


# 3.1. 變數

可以說「變數存值」，但另一種思考角度，變數是人類可讀的名稱，而它代表記憶體中的某些資料。

我們要花一點時間，從兔子洞裡窺一眼，這個洞是指標。別擔心。

您可以將記憶體視為一個大型的位元組（bytes）陣列\[32]。資料儲存在此「陣列」\[33]中。如果數字大於一個位元組，則以多個位元組來儲存。由於記憶體就像陣列，記憶體的每個位元組都可以由其索引來參照。記憶體中的這個索引也稱為位址、位置或指標。

當您在C中有變數時，該變數的值會存在記憶體中的某個位置、某個位址。（不然它還能在哪裡呢？）但是用數值位址來表示一個值是很困難的，所以我們為它取了一個名稱，這就是變數名稱。

我提出這一切的原因有兩個：

這將使以後更易於理解指標變數 — 它們是包含其他變數地址的變數！ 而且，它也會讓以後更容易理解指標。 所以變數是一些資料的名稱，這些資料儲存在記憶體的某個位置上。

<br>


# 3.1.1. 變數名稱

您可以使用範圍在 0-9、A-Z、a-z 之間與底線的任何字元作為變數名稱，規則如下：

* 變數開頭不能是數字0-9。
* 變數名稱的開頭不能是兩個底線。
* 變數名稱的開頭不能是底線加上大寫字母A-Z。

如果是 Unicode（萬國碼），請試試看。在§D.2的規格中，有一些規則會討論 Unicode 中哪些部分允許使用哪些 Unicode 的字碼點（codepoint）範圍，但是這裡寫不完，說不定你可能永遠都不會想要用到。


# 3.1.2 變數型別

根據您學過的語言，您可能知道型別（type）的概念。但C在型別上有點講究，所以我們應該去吃點東西。

這裡是一些型別的範例，有些是最基本的：

| 型別種類                   | 範例                | C 的型別                                                                  |
| ---------------------- | ----------------- | ---------------------------------------------------------------------- |
| 整數（Integer）            | `3490`            | `int`                                                                  |
| 浮點數（Floating point）    | `3.14159`         | `float`                                                                |
| 單一字元（single Character） | `'c'`             | `char`                                                                 |
| 字串（String）             | `"Hello, world!"` | `char *`[34](https://beej.us/guide/bgc/html/split/footnotes.html#fn34) |

如果你有需要，C 會盡力自動在大部分的數值型別之間轉換。除此之外，所有的型別轉換都是手動進行的，尤其是在字串和數字之間。 在C裡面，幾乎所有的型別都是這些型別的變體。 您必須先宣告變數，並告知C該變數所包含的型別，才能使用變數。一旦宣告了變數的型別，之後便不能在程式實際執行時變更。你要把它設定成它的原型，直到它脫離範圍再被重新吸收進宇宙。 讓我們使用之前的「Hello， world」程式碼，並加入一些變數：

```c
#include <stdio.h>

int main(void)
{
    int i;    // Holds signed integers, e.g. -3, -2, 0, 1, 10
    float f;  // Holds signed floating point numbers, e.g. -3.1416

    printf("Hello, World!\n");  // Ah, blessed familiarity
}
```

就是那裡！我們已經宣宣告了一些變數，但我們還沒有使用它們，它們也都還沒有初始化。一個代表整數、另一個代表浮點數（基本上，如果您學過數學，浮點數就是實數）。

未初始化的變數具有不定的數值\[35]，它們必須初始化，否則您必須假設它們會自動包含一些無意義的數字。

> 這是C可以「找到你」的地方之一，根據我的經驗，大多數情況下，不確定值為零……但可能會因執行而有所不同！即使您看到是零，也絕對不要假設初值是零。使用變數之前，一律要明確地將變數初始化為某個值\[36]。

這是什麼啊？你想要儲存一些數字在這些變數嗎？真是瘋了！

咱們開始吧：

```c
int main(void)
{
    int i;

    i = 2; // Assign the value 2 into the variable i

    printf("Hello, World!\n");
}
```

殺手啊，我們已儲存值了，咱們印出來吧。

我們將傳遞兩個驚人的參數給printf()函式，第一個參數是字串，用來描述要印的內容及列印方式（稱為格式化字串），而第二個參數是要印出來的數值，亦即變數 i 中的內容。 printf()會搜尋格式字串，找出以百分比符號(%)開頭的各種特殊序列，告知列印內容。例如，如果找到 %d，它會尋找下一個傳遞的參數，並將它列印為整數。如果找到 %f，就會將值列印為浮點數。如果找到 %s，就會列印字串。 所以，我們可以列印出各種型別的值，例如：

```c
#include <stdio.h>

int main(void)
{
    int i = 2;
    float f = 3.14;
    char *s = "Hello, world!";  // char * ("char pointer") is the string type

    printf("%s  i = %d and f = %f!\n", s, i, f);
}
```

而輸出如下：

```c
Hello, world!  i = 2 and f = 3.14!
```

這個方式的 printf( ) 可能類似你熟悉的其他程式語言，有各種格式化字串或是參數化的字串。

<br>


