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

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

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

相关标签:
13条回答
  • 2020-11-21 07:49

    A single quote is used for character, while double quotes are used for strings.

    For example...

     printf("%c \n",'a');
     printf("%s","Hello World");
    

    Output

    a  
    Hello World
    

    If you used these in vice versa case and used a single quote for string and double quotes for a character, this will be the result:

      printf("%c \n","a");
      printf("%s",'Hello World');
    

    output :

    For the first line. You will get a garbage value or unexpected value or you may get an output like this:

    While for the second statement, you will see nothing. One more thing, if you have more statements after this, they will also give you no result.

    Note: PHP language gives you the flexibility to use single and double-quotes easily.

    0 讨论(0)
  • 2020-11-21 07:53
    • 'x' is an integer, representing the numerical value of the letter x in the machine’s character set
    • "x" is an array of characters, two characters long, consisting of ‘x’ followed by ‘\0’
    0 讨论(0)
  • 2020-11-21 07:55
    1. single quote is for character;
    2. double quote is for string.
    0 讨论(0)
  • 2020-11-21 07:55

    In C, single-quotes such as 'a' indicate character constants whereas "a" is an array of characters, always terminated with the \0 character

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

    In C & C++ single quotes is known as a character ('a') whereas double quotes is know as a string ("Hello"). The difference is that a character can store anything but only one alphabet/number etc. A string can store anything. But also remember that there is a difference between '1' and 1. If you type cout<<'1'<<endl<<1; The output would be the same, but not in this case:

    cout<<int('1')<<endl<<int(1);
    

    This time the first line would be 48. As when you convert a character to an int it converts to its ascii and the ascii for '1' is 48. Same, if you do:

    string s="Hi";
    s+=48; //This will add "1" to the string
    s+="1"; This will also add "1" to the string
    
    0 讨论(0)
  • 2020-11-21 08:03

    Some compilers also implement an extension, that allows multi-character constants. The C99 standard says:

    6.4.4.4p10: "The value of an integer character constant containing more than one character (e.g., 'ab'), or containing a character or escape sequence that does not map to a single-byte execution character, is implementation-defined."

    This could look like this, for instance:

    const uint32_t png_ihdr = 'IHDR';
    

    The resulting constant (in GCC, which implements this) has the value you get by taking each character and shifting it up, so that 'I' ends up in the most significant bits of the 32-bit value. Obviously, you shouldn't rely on this if you are writing platform independent code.

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