Printing a char with printf

后端 未结 6 1494
粉色の甜心
粉色の甜心 2021-01-01 11:36

Are both these codes the same

char ch = \'a\';
printf(\"%d\", ch);

Will it print a garbage value?

I am confused about this

6条回答
  •  囚心锁ツ
    2021-01-01 12:02

    In C, character constant expressions such as '\n' or 'a' have type int (thus sizeof '\n' == sizeof (int)), whereas in C++ they have type char.

    The statement printf("%d", '\0'); should simply print 0; the type of the expression '\0' is int, and its value is 0.

    The statement printf("%d", ch); should print the integer encoding for the value in ch (for ASCII, 'a' == 97).

提交回复
热议问题