TopC++ 入門 › 参考 › ★ C と C++ の違い
★ SPECIAL

C と C++ の違い総覧

C のコードを書きながら「C++ ではどう書くのか」を 10 カテゴリで並べた一覧表。両方の書き方を知っていれば、旧コードのメンテも新規のモダン C++ も怖くありません。

1. 文字列

CC
char s[100]; strcpy(s, "hello"); strcat(s, " world"); int len = strlen(s); // ・バッファ溢れ注意
C++C++
std::string s = "hello"; s += " world"; int len = s.size(); // ・自動拡張、null 終端不要

2. 配列 / コンテナ

CC
int a[100]; // 固定長 int* p = malloc(n * sizeof(int)); // 可変長 ... free(p);
C++C++
std::array<int,100> a; // 固定長 std::vector<int> v(n); // 可変長・自動解放 std::map<int,std::string> m; // 連想配列もある

3. メモリ管理

CC
T* p = malloc(sizeof(T)); ... free(p); // 解放忘れ =リーク
C++C++
auto p = std::make_unique<T>(); // スコープ終端で自動 delete

4. 関数

CC
int add(int a, int b); // オーバーロード不可 double add_d(double a, double b); // 別名にする
C++C++
int add(int, int); // オーバーロード OK double add(double, double); template<class T> T add(T a, T b) { return a+b; } // テンプレート

5. エラー処理

CC
int open_file(const char* p, FILE** out) { *out = fopen(p, "r"); return *out ? 0 : -1; } if (open_file(...) < 0) { // 全階層で if }
C++C++
std::ifstream open_file(const std::string& p) { std::ifstream f(p); if (!f) throw std::runtime_error("open"); return f; // 中間層は if 不要 } try { ... } catch (...) { ... }

6. 入出力

CC
printf("x=%d, y=%.2f\n", x, y); // ・型と書式の不一致が UB
C++C++
std::cout << "x=" << x << ", y=" << y << "\n"; // ・型安全、ただし整形は面倒 // C++20 std::format で printf 相当

7. キャスト

CC
int x = (int)y; float* p = (float*)malloc(4);
C++C++
int x = static_cast<int>(y); auto p = new float; // キャスト不要 // ・4 種類を使い分け(static / dynamic / const / reinterpret)

8. 構造体 / クラス

CC
struct Point { int x, y; }; int point_area(const struct Point* p); // 関数は構造体の外
C++C++
struct Point { int x, y; int area() const { return x*y; } // メンバ関数 }; // class / private / public / 継承 / virtual

9. 定数

CC
#define MAX 100 const int size = 10; enum { Red, Green, Blue };
C++C++
constexpr int MAX = 100; constexpr int size = 10; enum class Color { Red, Green, Blue }; // 型安全

10. その他

  • nullptr (C++) vs NULL (C)。nullptr は型 std::nullptr_t を持つ。
  • bool: C++ は組み込み、C は stdbool.h が必要。
  • 参照 & (C++) — ポインタより安全な別名。C には無い。
  • ラムダ (C++11) — C には無い(関数ポインタで代替)。
  • STL(C++): コンテナ + アルゴリズム。C には標準化されていない。
  • 名前空間: C++ は namespace でスコープ分離。C には無い。
  • デフォルト引数: C++ は void f(int = 0); と書ける。
  • RAII: C++ 特有の資源管理パターン。C は手動。
  • 例外: C++ のみ(throw/try/catch)。C は setjmp/longjmp でごまかすしかない。
  • operator overload: C++ のみ。operator+ など。

まとめ — 移行のキーワード

  • char*std::string / std::string_view
  • malloc/freestd::vector / std::unique_ptr / RAII
  • printfstd::cout / std::format(C++20)
  • int err_code → 例外 / std::optional
  • (T)x キャスト → static_cast<T>(x)
  • typedefusing
  • 関数ポインタ → std::function / ラムダ
  • 手動ループ → std::sort / std::transform 等のアルゴリズム
どれも C++ の方が書くコードが減り型安全が強くなり、バグが減ります。ただし C の「値の流れが見える素朴さ」は失われるので、低レイヤ(OS カーネル、組込など)では意図的に C を選ぶ文化も残っています。