Printing a char with printf

后端 未结 6 1521
粉色の甜心
粉色の甜心 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

    Yes, it prints GARBAGE unless you are lucky.

    VERY IMPORTANT.

    The type of the printf/sprintf/fprintf argument MUST match the associated format type char.

    If the types don't match and it compiles, the results are very undefined.

    Many newer compilers know about printf and issue warnings if the types do not match. If you get these warnings, FIX them.

    If you want to convert types for arguments for variable functions, you must supply the cast (ie, explicit conversion) because the compiler can't figure out that a conversion needs to be performed (as it can with a function prototype with typed arguments).

    printf("%d\n", (int) ch)
    

    In this example, printf is being TOLD that there is an "int" on the stack. The cast makes sure that whatever thing sizeof returns (some sort of long integer, usually), printf will get an int.

    printf("%d", (int) sizeof('\n'))
    

提交回复
热议问题