從 Java 轉向 C,最大的心態轉變:**手動管理記憶體、無垃圾回收、編譯鏈接分離、標準庫極簡**。本文記錄入門第一步:最小程序、編譯運行、核心語法規範。
#include <stdio.h> // 預處理指令:包含標準輸入輸出庫頭文件
int main(void) { // 主函數:程序入口,返回 int 給操作系統
printf("test"); // 庫函數:向標準輸出寫入字符串
return 0; // 返回 0 表示成功
}
#include 是**預處理指令**(預處理器處理),非語句,**無分號**。main **必須且只能有一個**,程序入口。; 結尾**。Printf ≠ printf。/* ... */(C89),// ...(C99+)。# 源文件 hello.c
gcc hello.c -o hello # 編譯+鏈接 生成可執行文件 hello (Windows 為 hello.exe)
./hello # 運行 (Windows 直接輸入 hello)
# 輸出: test
四階段:預處理 (.i) → 編譯 (.s) → 組裝 (.o) → 鏈接 (可執行文件)。可單獨查看中間產物:gcc -E hello.c -o hello.i。
#include <stdio.h>
int main(void) {
float r, area, perimeter; // 聲明浮點變量
printf("請輸入半徑: ");
scanf("%f", &r); // &r 取地址,scanf 需地址寫入值
perimeter = 2 * 3.14159f * r;
area = 3.14159f * r * r;
printf("周長: %.2f, 面積: %.2f\n", perimeter, area);
return 0;
}
float:單精度浮點(4 字節),double 雙精度(8 字節)。scanf 格式串 %f 對應 float*,%lf 對應 double*。&:**取地址運算符**,獲取變量內存地址。#include <stdio.h>
int add(int a, int b); // 函數聲明(原型)
int main(void) {
int x, y, sum;
scanf("%d %d", &x, &y);
sum = add(x, y); // 調用
printf("和: %d\n", sum);
return 0;
}
int add(int a, int b) { // 定義
return a + b;
}
_,**首字符不能是數字**。區分大小寫。auto break case char const continue default do double else enum extern float for goto if int long register return short signed sizeof static struct switch typedef union unsigned void volatile while _Bool _Complex _Imaginary —— **不可作標識符**。snake_case,常量 UPPER_SNAKE,宏 UPPER_SNAKE。// 文件 1: main.c
#include "myhead.h" // 自定義頭文件
int main(void) { ... }
// 文件 2: utils.c
#include "myhead.h"
int add(int a, int b) { ... }
// 文件 3: myhead.h
#ifndef MYHEAD_H
#define MYHEAD_H
int add(int a, int b); // 僅聲明
#endif
// 編譯: gcc main.c utils.c -o app
.c)+ 頭文件(.h)。| Java | C |
|---|---|
System.out.println | printf |
Scanner.nextInt() | scanf("%d", &x) |
| 垃圾回收 | 手動 malloc/free |
| 引用類型 | 指針 int *p |
| 異常 try-catch | 返回碼/errno/長跳轉 |
| 類 | 結構體 struct + 函數指針 |
if/else、switch、循環)。