Cの書き方
よく使う文法・タグ・操作を、短い例で。42項目から探せます。
42 / 42項目
基本の形や関数内の抜粋を掲載しています。そのまま実行する例と準備方法は、各言語の「学ぶ」ページで確認できます。
変数と表示
型を指定して値を覚えます。
int age = 20;
printf("%d\n", age);条件分岐
条件が成立するかで処理を分けます。
int age = 20;
if (age >= 18) {
puts("成人");
} else {
puts("未成年");
}繰り返し
forで1から3まで表示します。
for (int i = 1; i <= 3; i++) {
printf("%d\n", i);
}関数
同じ計算を名前で呼び出します。
int add(int a, int b) { return a + b; }配列
同じ型の値を順番にまとめます。
int numbers[] = {10, 20, 30};
printf("%d\n", numbers[0]);構造体
関連する値をひとまとまりにします。
#include <stdio.h>
struct User { int age; };
int main(void) {
struct User user = {20};
printf("%d\n", user.age);
return 0;
}ポインター
値の置かれた場所を扱います。
int age = 20;
int *pointer = &age;
printf("%d\n", *pointer);コメント・定数
メモを残し、変更しない値を作る。
// 変更しない値
const int limit = 10;計算・比較・論理演算
足し算、等値、条件の組み合わせ。
int age = 20;
int total = 10 + 3;
int adult = age >= 18 && age < 65;型の変換
整数を小数として計算する。
int count = 3;
double average = (double)10 / count;文字列
終端のある文字配列で文字列を表す。
char name[] = "海";
printf("%s\n", name);stdio.hが必要です。%sは文字列の表示指定です。
strlen・strcmp
文字列の長さと一致を調べる。
char text[] = "hello";
size_t length = strlen(text);
int same = strcmp(text, "hello") == 0;string.hが必要です。strlenはバイト数です。
while
条件が成立している間繰り返す。
int i = 0;
while (i < 3) { i++; }switch
値で処理を分ける。
int day = 1;
switch (day) {
case 1: puts("月曜"); break;
default: puts("その他");
}break・continue
繰り返しを終了、または一回飛ばす。
for (int i = 0; i < 5; i++) {
if (i == 1) continue;
if (i == 3) break;
}関数の宣言
本体より前で関数の型を伝える。
int add(int a, int b);enum・typedef
候補や型に名前を付ける。
typedef enum { DRAFT, PUBLISHED } Status;
Status status = DRAFT;sizeof
値や型のサイズをバイトで得る。
int nums[] = {1, 2, 3};
size_t count = sizeof(nums) / sizeof(nums[0]);ポインターによる変更
参照先の値を書き換える。
int age = 20;
int *p = &age;
*p = 21;malloc・free
メモリーを確保し、使い終わったら解放する。
int *p = malloc(sizeof *p);
if (p != NULL) {
*p = 10;
free(p);
}stdlib.hが必要です。
ファイルを読む
ファイルを開き、1行読んで閉じる。
FILE *file = fopen("notes.txt", "r");
if (file != NULL) {
char line[100];
if (fgets(line, sizeof line, file)) puts(line);
fclose(file);
}stdio.hが必要です。
ヘッダーファイル
別の宣言を読み込む。
#include <stdio.h>
#include "my_functions.h"my_functions.hは自分で用意するヘッダーです。
数値を入力する
scanfの戻り値を確認して入力を受け取ります。
int age;
if (scanf("%d", &age) == 1) {
printf("%d\n", age);
}#include <stdio.h>が必要です。
1行を入力する
fgetsで配列の大きさまで文字列を読みます。
char name[40];
if (fgets(name, sizeof name, stdin) != NULL) {
printf("%s", name);
}#include <stdio.h>が必要です。末尾の改行が残ることがあります。
文字列に値を埋め込む
snprintfで大きさを指定して文字列を作ります。
char text[40];
int age = 20;
snprintf(text, sizeof text, "年齢: %d", age);#include <stdio.h>が必要です。長い結果は切り詰められます。
文字列の一部を探す
strstrで指定した文字列が含まれるか調べます。
const char *text = "hello world";
if (strstr(text, "world") != NULL) {
puts("見つかりました");
}#include <string.h>と#include <stdio.h>が必要です。
文字を数値にする
strtolで整数を読み、残った文字も確認します。
char *end;
long value = strtol("120", &end, 10);
if (*end == '\0') {
printf("%ld\n", value);
}#include <stdlib.h>と#include <stdio.h>が必要です。範囲外の値を扱う場合はerrnoも確認します。
短い条件分岐
条件によって使う値を切り替えます。
int age = 20;
const char *label = age >= 18 ? "成人" : "未成年";最低1回繰り返す
do whileは処理をしてから条件を確認します。
int count = 0;
do {
count++;
} while (count < 3);配列の要素数
配列全体の大きさを1要素の大きさで割ります。
int scores[] = {80, 90, 70};
size_t count = sizeof scores / sizeof scores[0];配列がポインタになる関数の引数では、この方法は使えません。
2次元配列
行と列を指定して値を取り出します。
int grid[2][3] = {{1, 2, 3}, {4, 5, 6}};
int value = grid[1][0];配列を関数に渡す
配列と一緒に要素数を渡します。
int total(const int values[], int count) {
int sum = 0;
for (int i = 0; i < count; i++) sum += values[i];
return sum;
}途中で戻る
条件を満たさないときはreturnで関数を終えます。
int divide(int value, int divisor) {
if (divisor == 0) return 0;
return value / divisor;
}この例では0を返します。実際には失敗を区別できる戻り値を決めます。
ポインタからメンバーを読む
構造体のポインタには矢印を使います。
struct User { int age; };
struct User user = {20};
struct User *ptr = &user;
int age = ptr->age;名前を指定して初期化
メンバー名を書いて値を設定します。
struct Point { int x; int y; };
struct Point point = {.x = 10, .y = 20};C99以降で使えます。
読み取り専用の参照
constを付けるとポインタ経由で値を変えられません。
int score = 80;
const int *ptr = &score;
int value = *ptr;NULLを確認する
使う前にポインタが有効か確認します。
int *ptr = NULL;
if (ptr != NULL) {
printf("%d\n", *ptr);
}#include <stdio.h>が必要です。
0で初期化した領域
callocで0に初期化された配列用の領域を作ります。
int *scores = calloc(3, sizeof *scores);
if (scores != NULL) {
scores[0] = 80;
free(scores);
}#include <stdlib.h>が必要です。
ファイルに書く
書き込みモードで開いて、最後に閉じます。
FILE *file = fopen("memo.txt", "w");
if (file != NULL) {
fputs("こんにちは\n", file);
fclose(file);
}#include <stdio.h>が必要です。wは既存の内容を消して書きます。
名前付きの状態で分岐
enumで状態に分かりやすい名前を付けます。
enum State { READY, DONE };
enum State state = READY;
if (state == READY) puts("準備中");#include <stdio.h>が必要です。
ヘッダーの重複を防ぐ
同じヘッダーを何度読み込んでも宣言が重複しません。
#ifndef USER_H
#define USER_H
int add(int a, int b);
#endifヘッダーファイルに書きます。USER_Hはファイルごとに変えます。
関数を変数で扱う
関数のアドレスを受け取って呼び出します。
int double_of(int x) { return x * 2; }
// 別の関数の中に書く
int (*action)(int) = double_of;
int result = action(3);関数定義と呼び出し側を分けて書きます。