Differences between single-quotes and double-quotes in C

前端 未结 5 433
梦如初夏
梦如初夏 2021-01-29 16:39

Recentely I have seen that if I use printf with \'foo\' I get a warning.

printf(\'numero\');

warning: character con

5条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-29 17:08

    There is a difference between character literals and string literals.

    To define a character literal you need to use single quotes. For example

    'A' is a character lietral. In C it has type int and even called like integer character constant. Its value is a numerical value of the internal representation of the character. You also may use multibyte character constants as for example 'AB' but its value is implementation defined.

    To define a string literal you need to use double quotes. For example "A" is a string literal. It has type of a character array of two characters (including the terminating zero) char[2]. You can imagine it like

    char s[2] = { 'A', '\0' };
    

    In expressions character arrays are converted to pointers to their first elements. Thus in an expression string literal is converted to type char *. You can imagine it like

    char s[2] = { 'A', '\0' };
    char *p = s;
    

    The first parameter of function printf has type const char *. Thus a string literal used as the argument may be used in function printf.

    For example

    printf( "A" );
    

    It is the same as

    printf( p );
    

    where p is defined as it is shown above.

    An integer character constant has type int. Using it as the argument can result in undefined behaviour because its value will be interpretated by function printf as an address of a string. So this statement

    printf( 'A' );
    

    is invalid. The printf will consider the internal value of the constant for example 65 (if to consider the ASCII table) as some memory address and will try to output what is stored at this address.

提交回复
热议问题