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

2018-12-31 03:21发布

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

12条回答
墨雨无痕
2楼-- · 2018-12-31 03:34

Single quote is used for character, while double quote used for string.

For example..

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

Output

a Hello World

If you used these in vice versa case and used single quote for string and double quote for character. Here, this will be result;

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

output :

for first line.You will have garbage value or unexpected.or you may be have output like this..

while for the second statement. You will see nothing. One thing more. If you have more statement after this. They will also give you no result.

Note : PHP language give you flexibility to use single and double quote easily.

查看更多
姐姐魅力值爆表
3楼-- · 2018-12-31 03:43

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.

查看更多
裙下三千臣
4楼-- · 2018-12-31 03:43

Single quotes are characters (char), double quotes are null-terminated strings (char *).

char c = 'x';
char *s = "Hello World";
查看更多
步步皆殇っ
5楼-- · 2018-12-31 03:46

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.

查看更多
步步皆殇っ
6楼-- · 2018-12-31 03:47

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' };
查看更多
若你有天会懂
7楼-- · 2018-12-31 03:51
  • '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’
查看更多
登录 后发表回答