auの日記

プログラミング初心者の日記。(auはハンドルネームです)

C言語のシングルクォーテーションとダブルクォーテーションは違う

auです。

今日はif文で条件式を書いた際に、文字区切り(c[i] == 'c'みたいな)をしようとした際に、シングルクォーテーションとダブルクォーテーションで結果が違うということに気づきました。紛らわしい。

確認する

ダブルクォーテーションを組みました。

#include <stdio.h>

int main(void) {
    char c[] = {"a", "b", "c", "d", "e"};

    for (int i = 0; i < 6; i++) {
        if (c[i] == "c") {
            printf("Cだよ!!!\n");
        }
    }

    return 0;
} 

// コンパイル結果
9-2.c:4:22: warning: excess elements in char array initializer
    char c[] = {"a", "b", "c", "d", "e"};
                     ^~~
9-2.c:7:18: warning: result of comparison against a string literal is unspecified
      (use strncmp instead) [-Wstring-compare]
        if (c[i] == "c") {
                 ^  ~~~
9-2.c:7:18: warning: comparison between pointer and integer ('int' and 'char *')
        if (c[i] == "c") {
            ~~~~ ^  ~~~
3 warnings generated.

Warningで返されてしまいました・・・

シングルクォーテーションで組んでみます。

#include <stdio.h>

int main(void) {
    char c[] = {'a', 'b', 'c', 'd', 'e'};

    for (int i = 0; i < 6; i++) {
        if (c[i] == 'c') {
            printf("Cだよ!!!\n");
        }
    }

    return 0;
} 

// 実行結果
Cだよ!!!

やったぜ。「char c[] = {'a', 'b', 'c', 'd', 'e'};」のところも「'」にしないとWarningで返されました。

調べてみると、どうやら""''では文字型数値型に変化するみたいです。それぞれ比較する場合、同じ型でないと比較ができないため、このような結果になっているそうです。

また、この場合比較しているのは文字コード(ASCII)です。ややこしい。

比較をした際に警告などが出る場合は、クォーテーションの確認をしてみてください。