跳轉到內容

軟體工程師手冊/語言詞典/C

來自華夏公益教科書,開放的世界,開放的書籍

在這裡尋找 C 的故事

C 是一種完整的過程式語言。

執行入口點

[編輯 | 編輯原始碼]

可執行檔案從 main() 方法開始。

一般語法

[編輯 | 編輯原始碼]

典型的語句以分號結束。要將 b 賦值給 a,請使用

a = b;

塊註釋以 /* 開始,以 */ 結束,可以跨越多行。

/*
 * this is a block comment
 */

變數宣告

[編輯 | 編輯原始碼]

宣告需要出現在作用域的頂部。

將 i 宣告為整數

int i;

將 i 宣告為整數,並賦予其初始值為 0

int i = 0;

方法宣告/實現

[編輯 | 編輯原始碼]

方法透過指定方法的介面來宣告。

return_type function_name(argument_1_type arg_1_name,
                          argument_2_type arg_2_name);

方法實現重複了許多相同的資訊

return_type function_name(argument_1_type arg_1_name, 
                          argument_2_type arg_2_name)
{
    // work with arg_1_name, arg_2_name, and default_arg_name
    // depending on the argument types the variables are passed by 
    //   value, reference, or are constant
    // don't forget to return something of the return type
    return 36;
}

範圍由花括號定義。

{ // this the beginning of a scope
    // the scope is about to end
}

條件語句

[編輯 | 編輯原始碼]

當且僅當 A 等於 B 時,將 C 賦值給 D,否則,將 E 賦值給 F。

if (A == B)
{
    D = C;
    // more code can be added here.  It is used if and only if A is equal to B
}
else
{
    F = E;
    // more code can be added here.  It is used if and only if A is not equal to B
}

或者

if (A == B)
    D = C; //more lines of code are not permitted after this statement
else
    F = E;

或者,可以使用 switch 語句來執行多個選擇操作。此示例將數字輸入轉換為文字。

switch (number_value)
{
    case 37:
        text = "thirty-seven";
        break; // this line prevents the program from writing over this value with the
               //   following code
    case 23:
        text = "twenty-three";
        break;
    default: // this is used if none of the previous cases contain the value
        text = "unknown number";
}

迴圈語句

[編輯 | 編輯原始碼]

此程式碼從 0 到 9 計數,將陣列的內容加起來。

int i = 0;
for (int index = 0; index < 10; index = index + 1)
{
    i = array[index];
}

此程式碼重複,直到找到數字 4 為止。如果它執行到陣列末尾,則可能存在問題。

int index = 0;
while (4 != array[index])
{
    index = index + 1;
}

此程式碼在進行檢查之前遞增計數器,因此它從元素 1 開始。

int index = 0;
do
{
    index = index + 1;
}
while (4 != array[index]);

輸出語句

[編輯 | 編輯原始碼]
printf ("%s","Hello world!\n");

結構體

演算法

[編輯 | 編輯原始碼]

實現您自己的演算法,或者找到一個庫。

垃圾回收

[編輯 | 編輯原始碼]

垃圾回收是手動的。

物理結構

[編輯 | 編輯原始碼]

通常,介面在實現之前定義在標頭檔案中(通常為 *.h)或在實現之上。實現檔案通常命名為 *.c。有用的類集合可以編譯成庫,通常為 *.dll、*.a 或 *.so,這些庫可以編譯成可執行檔案(靜態連結)或動態使用(動態連結)。

不要混淆這兩者

=  // assignment
== // comparison, is equal to

通常,使用您不想要的那個會編譯,併產生您沒有預期的結果。

一個好的做法是編寫:if(CONSTANT == variable) 而不是 if(variable == CONSTANT),因為編譯器會捕獲 if(CONSTANT = variable),但不會捕獲 if(variable = CONSTANT)。

使用生成大量有用警告的編譯器,即使程式碼有效。您也可以/使用 'lint' 等程式。這將幫助您避免簡單的錯誤,例如上面提到的錯誤“if ( x = 1 )”而不是“if ( x == 1 )”。

陣列從索引 0 開始。

網路參考

[編輯 | 編輯原始碼]

列出網路上的其他參考資料。請包括參考資料適用於什麼級別的讀者。(初學者/中級/高階)

書籍和文章

[編輯 | 編輯原始碼]

需要參考

C 程式語言:(示例連結:http://cm.bell-labs.com/cm/cs/cbook/ )

華夏公益教科書