Printing a char with printf

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

    #include 
    #include 
    
    int func(char a, char b, char c) /* demonstration that char on stack is promoted to int !!!
                                        note: this promotion is NOT integer promotion, but promotion during handling of the stack. don't confuse the two */
    {
      const char *p = &a;
      printf("a=%d\n"
             "b=%d\n"
             "c=%d\n", *p, p[-(int)sizeof(int)], p[-(int)sizeof(int) * 2]); // don't do this. might probably work on x86 with gcc (but again: don't do this)
    }
    
    
    int main(void)
    {
      func(1, 2, 3);
    
      //printf with %d treats its argument as int (argument must be int or smaller -> works because of conversion to int when on stack -- see demo above)
      printf("%d, %d, %d\n", (long long) 1, 2, 3); // don't do this! Argument must be int or smaller type (like char... which is converted to int when on the stack -- see above)
    
    
    
      // backslash followed by number is a oct VALUE
      printf("%d\n", '\377');             /* prints -1   -> IF char is signed char: char literal has all bits set and is thus value -1.
                                                         -> char literal is then integer promoted to int. (this promotion has nothing to do with the stack. don't confuse the two!!!) */
                                          /* prints 255  -> IF char is unsigned char: char literal has all bits set and is thus value 255.
                                                         -> char literal is then integer promoted to int */
    
    
      // backslash followed by x is a hex VALUE
      printf("%d\n", '\xff');             /* prints -1   -> IF char is signed char: char literal has all bits set and is thus value -1.
                                                         -> char literal is then integer promoted to int */
                                          /* prints 255  -> IF char is unsigned char: char literal has all bits set and is thus value 255.
                                                         -> char literal is then integer promoted to int */
    
    
      printf("%d\n", 255);                // prints 255
    
    
      printf("%d\n", (char)255);          // prints -1   -> 255 is cast to char where it is -1
      printf("%d\n", '\n');               // prints 10   -> Ascii newline has VALUE 10. The char 10 is integer promoted to int 10
      printf("%d\n", sizeof('\n'));       // prints 4    -> Ascii newline is char, but integer promoted to int. And sizeof(int) is 4 (on many architectures)
      printf("%d\n", sizeof((char)'\n')); // prints 1    -> Switch off integer promotion via cast!
    
      return 0;
    }
    

提交回复
热议问题