C言語の変換指定子
auです。
今回は、"printf("%d\n")"の中にある"%d"の部分について書きたいと思います。
変換指定子とは
%dや%cなどの名前は変換指定子です。
入力する文字列の変数の型を指定するために変換指定子というものを使います。
例えば...
int型の場合には"%d"
char*型(文字列)の場合には"%s"
など、使える型が決まっています。
%dで文字を表示しようとしてみます。
#include<stdio.h> int main(void) { printf("%d\n", "Hello"); return 0; } // 実行結果 warning: format ‘%d’ expects argument of type ‘int’, but argument 2 has type ‘char *’ [-Wformat=] printf("%d\n", "Hello"); ^
%dはint型で、それはchar型だと警告されました。
次に、%sで実行してみます。
#include<stdio.h> int main(void) { printf("%s\n", "Hello"); return 0; } //実行結果 Hello
今回はちゃんと実行できました。
ちなみに、Helloも""(ダブルクォーテーション)で囲われてないとエラーになるので、文字列はしっかりと""で囲みましょう。
#include<stdio.h> int main(void) { printf("%s\n", Hello); return 0; } // 実行結果 error: ‘Hello’ undeclared (first use in this function) printf("%s\n", Hello); ^ scanf.c:4:20: note: each undeclared identifier is reported only once for each function it appears in