C語言速查表



這份C語言速查錶快速概述了C語言的概念,從基礎到高階。這份速查表對學生、開發者和正在準備面試的人非常有用。通讀這份速查表,學習C程式語言的所有基本和高階概念。

C language cheat sheet

C程式的基本結構

C程式的基本結構讓你瞭解在C語言中編寫程式所需的基本語句。以下是C程式的基本結構:

// Preprocessor directive/header file inclusion section
#include <stdio.h>

// Global declaration section

// the main() function
int main() {
   // Variable declarations section 
   int x, y;
    
   // other code statements section

   // Return o
   return 0;
}
// Other user-defined function definition section

#include <stdio.h>

#include 是一個預處理器指令,它包含C程式中的標頭檔案。stdio.h 是一個頭檔案,其中定義了所有與輸入輸出相關的函式。

main() 函式

main() 函式是C程式的入口點,程式的執行從main() 函式開始。

以下是main() 函式的語法:

int main() {
   return 0;
}

註釋

C語言中有兩種型別的註釋。單行註釋和多行註釋。編譯器會忽略註釋。

單行註釋

使用 // 來編寫單行註釋。

// This is a single-line comment

多行註釋

在文字之前和之後使用 /* 和 */ 來在C語言中編寫多行註釋。

/*
This is line 1
This is line 2
..
*/

列印(printf() 函式)

printf() 函式是一個庫函式,用於在控制檯輸出上列印格式化的文字。每當你想列印任何內容時,都使用 printf()。

示例

printf("Hello world");

使用者輸入(scanf() 函式)

scanf() 函式用於從使用者處獲取各種型別的輸入。

以下是 scanf() 函式的語法:

scanf("format_specifier", &variable_name);

格式說明符

以下是printf()scanf() 函式中使用的C格式說明符列表,用於列印/輸入特定型別的數值。

格式說明符 型別
%c 字元
%d 帶符號整數
%e 或 %E 浮點數的科學計數法
%f 浮點值
%g 或 %G 類似於 %e 或 %E
%hi 帶符號整數(短整型)
%hu 無符號整數(短整型)
%i 無符號整數
%l 或 %ld 或 %li 長整型
%lf 雙精度浮點數
%Lf 長雙精度浮點數
%lu 無符號整型或無符號長整型
%lli 或 %lld 長長整型
%llu 無符號長長整型
%o 八進位制表示
%p 指標
%s 字串
%u 無符號整型
%x 或 %X 十六進位制表示

示例

#include <stdio.h>

int main(){

   int age = 18;

   float percent = 67.75;

   printf("Age: %d \nPercent: %f", age, percent);

   return 0;
}

輸出

Age: 18 
Percent: 67.750000

資料型別

資料型別指定儲存在變數中的資料的型別和大小。資料型別分為3類:

  • 基本資料型別
  • 派生資料型別
  • 使用者自定義資料型別

基本資料型別

基本資料型別是C語言中的內建資料型別,它們也用於建立派生資料型別。

資料型別 名稱 描述
int 整數 表示整數值
char 字元 表示單個字元
float 浮點數 表示浮點值

派生資料型別

派生資料型別是從基本資料型別派生出來的。派生資料型別包括:

  • 陣列
  • 指標

使用者自定義資料型別

使用者自定義資料型別是由程式設計師建立的,用於處理不同型別的資料,並根據需求而定。使用者自定義資料型別包括:

  • 結構體
  • 聯合體
  • 列舉

基本的輸入輸出

對於C語言中的基本輸入和輸出,我們使用printf()scanf() 函式。

printf() 函式用於在控制檯上列印格式化的文字。

printf("Hello world");

scanf() 函式用於從使用者處獲取輸入。

scanf("%d", &x); // Integer input
scanf("%f", &y); // float input
scanf("%c", &z); // Character Input
scanf("%s", name); // String input

基本輸入輸出示例

#include <stdio.h>

int main() {
   int num;

   printf("Input any integer number: ");
   scanf("%d", &num);

   printf("The input is: %d\n", num);

   return 0;
} 

輸出

Input any integer number: The input is: 0

識別符號

C識別符號是使用者為變數、常量、函式等定義的名稱。定義識別符號的規則如下:

  • 關鍵字不能用作識別符號。
  • 識別符號中只允許使用字母、下劃線符號 (_) 和數字。
  • 識別符號必須以字母或下劃線開頭。
  • 同一個識別符號不能用作兩個實體的名稱。
  • 識別符號應該有意義且具有描述性。

有效識別符號示例

age, _name, person1, roll_no

關鍵字

C關鍵字是C編譯器中的保留字,它們用於特定目的,不能用作識別符號。

以下是C語言中的關鍵字:

autodoubleintstruct
breakelselongswitch
caseenumregistertypedef
charexternreturnunion
continueforsignedvoid
doifstaticwhile
defaultgotosizeofvolatile
constfloatshortunsigned

變數

C變數是賦予儲存區域的名稱,我們的程式可以使用它來訪問和操作資料。

宣告變數的語法

data_type variable_name;

轉義序列

轉義序列是特殊字元後跟轉義符(反斜槓 \)。轉義序列具有特殊含義,用於列印那些無法正常列印的字元。

以下是C語言中的轉義序列列表:

轉義序列 含義
\\ \字元
\' '字元
\" "字元
\? ?字元
\a 警告或鈴聲
\b 退格
\f 換頁
\n 換行
\r 回車
\t 水平製表符
\v 垂直製表符
\ooo 一位到三位八進位制數
\xhh ... 一位或多位十六進位制數

運算子

運算子是用於執行特定數學或邏輯運算的特殊符號。

以下是C語言中使用的運算子:

運算子 符號 描述
賦值運算子 =, +=, -=, <<= 執行賦值操作,即為變數賦值。
算術運算子 +, -, *, /, % 執行算術運算。
關係運算符 <, >, <=, >=, ==, != 對兩個運算元進行比較。
邏輯運算子 &&, ||, ! 執行邏輯運算,例如邏輯與、或和非。
位運算子 &, ^, |, <<, >>, ~ 執行位運算。
三元運算子 ? : 執行條件操作以進行決策。
其他運算子 ,sizeof,&,*,⇒,。 用於執行各種其他操作。

運算子示例

result = num1 + num2;
if(result >=10){
   printf("Greater than 10.");
}

條件語句

C語言提供以下條件語句:

  • if語句
  • if-else語句
  • if-else-if語句
  • 巢狀if-else語句
  • switch語句
  • 三元運算子

if語句

一個if語句由一個布林表示式和一個或多個語句組成。

if語句的語法如下:

if(boolean_expression) {
   /* statement(s) will execute if the boolean expression is true */
}

if-else語句

一個if-else語句可以後跟一個可選的else語句,當布林表示式為假時執行。

if語句的語法如下:

if (Boolean expr){
   Expression;
   . . .
}
else{
   Expression;
   . . .
}

if-else-if語句

if-else-if語句也稱為階梯式if-else。當條件不為真時,它用於檢查多個條件。

if-else-if語句的語法:

if(condition1){
}
else if(condition2){
}
…
else{
}

巢狀if語句

透過使用巢狀if語句,你可以在另一個if或else-if語句內使用一個if或else-if語句。

巢狀if語句的語法:

if (expr1){
   if (expr2){
      block to be executed when 
      expr1 and expr2 are true
   }
   else{
      block to be executed when 
      expr1 is true but expr2 is false
   }        
}

switch語句

一個switch語句允許測試變數與值的列表是否相等。

switch語句的語法如下:

switch (Expression){

   // if expr equals Value1
   case Value1: 
      Statement1;
      Statement2;
      break;
   
   // if expr equals Value2
   case Value2: 
      Statement1;
      Statement2;
      break;
      .
      . 
   // if expr is other than the specific values above
   default:
      Statement1;
      Statement2;
}

三元運算子

三元運算子(?:) 也稱為條件運算子。它可以用作if-else語句的替代。

三元運算子的語法如下:

(condition) ? true_block: false_block;

迴圈

C語言迴圈用於分別執行一個或多個語句塊指定的次數,或直到達到某個條件。以下是C語言中的迴圈語句:

  • while迴圈
  • do...while迴圈
  • for迴圈

while迴圈

while迴圈是一種入口控制迴圈,其中在執行迴圈體之前檢查條件。

while迴圈的語法如下:

while(test_condition){
   // Statement(s);
}

do…while迴圈

do…while迴圈是一種出口控制迴圈,其中在檢查條件之前執行迴圈體。

do…while迴圈的語法如下:

do{
   // Statement(s);
}while(test_condition);

for迴圈

for迴圈也是一種入口控制迴圈,其中元素(初始化、測試條件和增量)放在一起,在for關鍵字的括號內形成for迴圈。

for迴圈的語法如下:

for(initialization ; test condition ; increment){
   // Statement (s);
}

跳轉語句

跳轉語句用於將程式的流程從一個地方轉移到另一個地方。以下是C語言中的跳轉語句:

  • goto語句
  • break語句
  • continue語句

goto語句

goto語句將程式的控制轉移到特定的標籤。你需要定義一個後跟冒號(:)的標籤。goto語句可以向上或向下轉移程式的流程。

goto語句的語法如下:

標籤名

//Statement(s)
if(test_condition){
   goto label_name;
}

break語句

break語句可以與迴圈和switch語句一起使用。break語句終止迴圈執行並將程式的控制轉移到迴圈體之外。

break語句的語法如下:

while(condition1){
   . . .
   . . .
   if(condition2)
   break;
      . . .
      . . .
}

continue語句

continue語句用於跳過當前迭代中迴圈內其餘語句的執行,並將其轉移到下一個迴圈迭代。

continue語句的語法如下:

while (expr){
   . . .
   . . .
   if (condition)
      continue;
   . . .
}

使用者自定義函式

使用者自定義函式由使用者定義,用於執行特定任務以實現程式碼可重用性和模組化。

使用者自定義函式示例

#include <stdio.h>

// Function declaration
int add(int, int);

// Function definition
int add(int a, int b) { return (a + b); }

int main() {
   int num1 = 10, num2 = 10;
   int res_add;

   // Calling the function
   res_add = add(num1, num2);

   // Printing the results
   printf("Addition is : %d\n", res_add);

   return 0;
}

輸出

Addition is : 20

陣列

陣列是相似資料型別的多個數據項的集合,它們儲存在連續的記憶體位置。資料項可以是基本資料型別(int、float、char),也可以是使用者定義的型別,例如結構體或指標可以儲存在陣列中。

C語言陣列可以分為兩種型別:

  • 一維陣列 - 一維陣列是相同資料型別的單個數據項列表。
  • 多維陣列 - 多維陣列,例如二維陣列,是陣列的陣列。

陣列語法

以下是不同型別陣列宣告的語法:

type array_name [size1];   // One-dimensional array
type array_name [size1][size2];   // Two-dimensional arrays
type array_name [size1][size2][size3];    // Three-dimensional arrays

一維陣列示例

#include <stdio.h>

int main(){
   int numbers[5] = {10, 20, 30, 40, 50};

   int i;  // loop counter

   // Printing array elements
   printf("The array elements are : ");
   for (i = 0; i < 5; i++) {
      printf("%d ", numbers[i]);
   }

   return 0;
}

輸出

The array elements are : 10 20 30 40 50 

二維陣列示例

#include <stdio.h>

int main () {

   /* an array with 5 rows and 2 columns*/
   int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
   int i, j;
 
   /* output each array element's value */
   for ( i = 0; i < 5; i++ ) {
      for ( j = 0; j < 2; j++ ) {
         printf("a[%d][%d] = %d\n", i,j, a[i][j] );
      }
   }
   
   return 0;
}

輸出

a[0][0] = 0
a[0][1] = 0
a[1][0] = 1
a[1][1] = 2
a[2][0] = 2
a[2][1] = 4
a[3][0] = 3
a[3][1] = 6
a[4][0] = 4
a[4][1] = 8

字串

C語言字串是一系列字元,即char資料型別的陣列,以“空字元”(用'\0'表示)結尾。要使用scanf()和printf()函式讀取和列印字串,你必須使用“%s”格式說明符。

字串宣告

char string_name[size];

讀取字串

scanf("%s", string_name);

列印字串

printf("%s", string_name);

C語言字串示例

#include <stdio.h>

int main() {
   char name[20];

   printf("Enter a name: ");
   scanf("%s", name);

   printf("You entered: %s", name);

   return 0;
}

字串函式

C標準庫string.h提供各種函式來處理字串。以下是C語言字串函式的列表:

序號 函式 描述
1 char *strcat src指向的字串附加到dest指向的字串的末尾。
2 char *strncat src指向的字串附加到dest指向的字串的末尾,最多n個字元長。
3 char *strchr( 在引數str指向的字串中搜索字元c(無符號字元)的第一次出現。
4 int strcmp str1指向的字串與str2指向的字串進行比較。
5 int strncmp 最多比較str1str2的前n個位元組。
6 int strcoll 比較字串str1str2。結果取決於位置的LC_COLLATE設定。
7 char *strcpy src指向的字串複製到dest
8 char *strncpy 最多將src指向的字串中的n個字元複製到dest
9 size_t strcspn 計算str1的初始段的長度,該段完全由str2中不存在的字元組成。
10 char *strerror 在一個內部陣列中搜索錯誤號errnum,並返回指向錯誤訊息字串的指標。
11 size_t strlen 計算字串str的長度,直到但不包括終止空字元。
12 char *strpbrk 在字串str1中查詢與str2中指定的任何字元匹配的第一個字元。
13 char *strrchr 在引數str指向的字串中搜索字元c(無符號字元)的最後一次出現。
14 size_t strspn 計算str1的初始段的長度,該段完全由str2中的字元組成。
15 char *strstr 查找出現在字串haystack中的整個字串needle(不包括終止空字元)的第一次出現。
16 char *strtok 將字串str分解成一系列由delim分隔的標記。
17 size_t strxfrm 將字串src的前n個字元轉換為當前區域設定,並將它們放在字串dest中。

結構體

C語言結構體是不同資料型別的集合。結構體被認為是使用者定義的資料型別,你可以在其中組合不同資料型別的資料項。

結構體宣告語法

struct struct_name {
   type1 item1;
   type2 item2;
   .
   .
}structure_variable;

結構體示例

#include <stdio.h>

struct book{
   char title[10];
   char author[20];
   double price;
   int pages;
};

int main(){
   struct book book1 = {"Learn C", "Dennis Ritchie", 675.50, 325};
   
   printf("Title:  %s \n", book1.title);
   printf("Author: %s \n", book1.author);
   printf("Price:  %lf\n", book1.price);
   printf("Pages:  %d \n", book1.pages);
   printf("Size of book struct: %d", sizeof(struct book));
   return 0;
}

輸出

Title:  Learn C 
Author: Dennis Ritchie 
Price:  675.500000
Pages:  325 
Size of book struct: 48

聯合體

C語言聯合體是一種使用者定義的資料型別,允許在同一個記憶體位置儲存不同資料型別的資料項集合。

聯合體宣告語法

union [union tag]{
   member definition;
   member definition;
   ...
   member definition;
} [one or more union variables];

聯合體示例

#include <stdio.h>

union Data{
   int i;
   float f;
};

int main(){
   union Data data;        
   
   data.i = 10;
   data.f = 220.5;
   
   printf("data.i: %d \n", data.i);
   printf("data.f: %f \n", data.f);
   return 0;
}

輸出

data.i: 1130135552 
data.f: 220.500000 

列舉 (enums)

C語言列舉 (enum)是一種列舉資料型別,它由一組整型常量組成。

列舉宣告語法

enum myenum {val1, val2, val3, val4};

列舉示例

#include <stdio.h>

enum status_codes { OKAY = 1, CANCEL = 0, ALERT = 2 };

int main() {
   // Printing values
   printf("OKAY = %d\n", OKAY);
   printf("CANCEL = %d\n", CANCEL);
   printf("ALERT = %d\n", ALERT);

   return 0;
}

輸出

OKAY = 1
CANCEL = 0
ALERT = 2

指標

C語言指標是派生資料型別,用於儲存另一個變數的地址,也可以用於訪問和操作儲存在該位置的變數資料。

指標宣告語法

data_type *pointer_name;

指標初始化語法

如果你聲明瞭一個指標,以下是使用另一個變數的地址初始化指標的語法:

pointer_name = &variable_name;

指標示例

#include <stdio.h>

int main() {
   int x = 10;

   // Pointer declaration and initialization
   int * ptr = & x;

   // Printing the current value
   printf("Value of x = %d\n", * ptr);

   // Changing the value
   * ptr = 20;

   // Printing the updated value
   printf("Value of x = %d\n", * ptr);

   return 0;
}

輸出

Value of x = 10
Value of x = 20

指標型別

C語言中有各種型別的指標。它們是:

動態記憶體分配

變數的記憶體是在編譯時宣告的。C語言提供一些動態記憶體分配函式,允許在執行時為變數分配記憶體。

動態記憶體分配函式:

  • malloc()
  • calloc()
  • realloc()
  • free()

malloc()函式

malloc()函式分配請求的記憶體(指定大小的塊數),並返回指向它的指標。

malloc() 函式的語法如下:

malloc (size_t size);
calloc() Function

calloc() 函式

calloc() 函式分配請求的記憶體(指定大小的塊數),並返回 void 指標。calloc() 函式將分配的記憶體設定為零。

calloc() 函式的語法如下:

void *calloc(size_t nitems, size_t size)

realloc() 函式

realloc() 函式嘗試重新調整由指標指向的記憶體塊的大小,該指標之前已透過呼叫 malloc() 或 calloc() 函式分配。

realloc() 函式的語法如下:

void *calloc(size_t nitems, size_t size)

free() 函式

free() 函式釋放之前透過呼叫 calloc()、malloc() 或 realloc() 分配的記憶體。

realloc() 函式的語法如下:

void *calloc(size_t nitems, size_t size)

檔案處理

檔案處理指的是對檔案執行各種操作,例如建立、寫入、讀取、刪除、移動、重新命名檔案等。C 語言提供了各種檔案處理函式。

檔案操作

以下是可以使用 C 語言檔案處理函式對檔案執行的操作:

  • 建立新檔案
  • 開啟現有檔案
  • 向檔案寫入資料
  • 向檔案追加資料
  • 從檔案讀取資料
  • 重新命名檔案
  • 刪除檔案
  • 關閉檔案

檔案處理函式

以下是 C 語言中檔案處理函式的列表:

函式 描述
fopen() 建立並以各種模式開啟檔案。
fclose() 關閉檔案。
fputc()fputs()fprintf() 向檔案寫入資料。
fgetc()fgets()fscanf() 從檔案讀取資料。
fwrite()fread() 向二進位制檔案寫入和讀取資料。
rename() 重新命名檔案。
remove() 刪除檔案。

檔案處理示例

這是一個 C 語言檔案處理的示例:

#include <stdio.h>
#include <stdlib.h>

int main() {
   FILE *file;
   char file_name[] = "my_file.txt";
   char write_data[100] = "Tutorials Point";
   char read_data[100];

   // Opening file in write mode
   file = fopen("file_name.txt", "w");
   if (file == NULL) {
      printf("Error\n");
      return 1;
   }
   // Writing to the file
   fprintf(file, "%s", write_data);
   // Closing the file
   fclose(file);

   // Again, opening the file in read mode
   file = fopen("file_name.txt", "r");
   if (file == NULL) {
      printf("Error.\n");
      return 1;
   }

   // Reading data from the file
   if (fgets(read_data, 100, file) != NULL) {
      // Printing it on the screen
      printf("File's data:\n%s\n", read_data);
   }
   fclose(file);

   return 0;
}

輸出

File's data:
Tutorials Point

預處理器指令

預處理器指令是預編譯的一部分,以井號 (#) 字元開頭。這些指令指示編譯器在開始編譯過程之前展開 include 並擴充套件程式碼。

以下是預處理器指令的列表:

指令 描述
#define 替換預處理器宏。
#include 插入來自另一個檔案的特定標頭檔案。
#undef 取消定義預處理器宏。
#ifdef 如果定義了此宏,則返回 true。
#ifndef 如果未定義此宏,則返回 true。
#if 測試編譯時條件是否為 true。
#else #if 的替代方案。
#elif #else 和 #if 合併成一條語句。
#endif 結束預處理器條件。
#error 在 stderr 上列印錯誤訊息。
#pragma 使用標準化方法向編譯器發出特殊命令。

預處理器指令示例

這是一個 #define 的示例,它是 C 語言中的一種預處理器指令:

#define MAX_ARRAY_LENGTH 20

標準庫

以下是常用庫(C 標頭檔案)的列表:

標頭檔案 用途
stdio.h 提供標準輸入和輸出函式。
string.h 提供各種字串操作函式。
math.h 提供數學運算函式。
stdlib.h 提供各種用於記憶體分配、型別轉換等的實用函式。
time.h 提供與日期時間相關的函式。
廣告