軟體工程師手冊/語言字典/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/)