Single quotes vs. double quotes in C or C++

前端 未结 13 1212
别那么骄傲
别那么骄傲 2020-11-21 07:14

When should I use single quotes and double quotes in C or C++ programming?

相关标签:
13条回答
  • 2020-11-21 08:05

    Double quotes are for string literals, e.g.:

    char str[] = "Hello world";
    

    Single quotes are for single character literals, e.g.:

    char c = 'x';
    

    EDIT As David stated in another answer, the type of a character literal is int.

    0 讨论(0)
  • 2020-11-21 08:07

    I was poking around stuff like: int cc = 'cc'; It happens that it's basically a byte-wise copy to an integer. Hence the way to look at it is that 'cc' which is basically 2 c's are copied to lower 2 bytes of the integer cc. If you are looking for a trivia, then

    printf("%d %d", 'c', 'cc'); would give:
    

    99 25443

    that's because 25443 = 99 + 256*99

    So 'cc' is a multi-character constant and not a string.

    Cheers

    0 讨论(0)
  • 2020-11-21 08:07

    Single quotes are for a single character. Double quotes are for a string (array of characters). You can use single quotes to build up a string one character at a time, if you like.

    char myChar     = 'A';
    char myString[] = "Hello Mum";
    char myOtherString[] = { 'H','e','l','l','o','\0' };
    
    0 讨论(0)
  • 2020-11-21 08:09

    Use single quote with single char as:

    char ch = 'a';
    

    here 'a' is a char constant and is equal to the ASCII value of char a.

    Use double quote with strings as:

    char str[] = "foo";
    

    here "foo" is a string literal.

    Its okay to use "a" but its not okay to use 'foo'

    0 讨论(0)
  • 2020-11-21 08:09

    Single quotes are denoting a char, double denote a string.

    In Java, it is also the same.

    0 讨论(0)
  • 2020-11-21 08:12

    In C and in C++ single quotes identify a single character, while double quotes create a string literal. 'a' is a single a character literal, while "a" is a string literal containing an 'a' and a null terminator (that is a 2 char array).

    In C++ the type of a character literal is char, but note that in C, the type of a character literal is int, that is sizeof 'a' is 4 in an architecture where ints are 32bit (and CHAR_BIT is 8), while sizeof(char) is 1 everywhere.

    0 讨论(0)
提交回复
热议问题