Home > Software design >  character '\0' vs string "\0" [closed]
character '\0' vs string "\0" [closed]

Time:10-01

An online testing system expects my code to output the number 10.

It accepts:

printf("%d",10)
printf("%c%c\0", '1', '0')
printf("%c%c\0something", '1', '0')
printf("%c%c%s", '1', '0', "\0")

But rejects:

printf("%c%c%c", '1', '0', '\0')
printf("%c%c%c", '1', '0', 0)
putchar('1');putchar('0');putchar('\0');
putchar('1');putchar('0');putchar(0);

What is the difference between printing "\0" and '\0'?

CodePudding user response:

Your online testing system is expecting to see the character sequence {'1', '0'}, but you are sending it the sequence {'1', '0', NUL }. You're trying to print the string terminator in addition to the string characters.

The string "10" is internally represented as the character sequence {'1', '0', NUL}, but when you display it with printf( "%s", "10" );, that trailing 0 isn't written to the output stream. The terminator is only there to mark the end of the string - it's never displayed or copied.

CodePudding user response:

C-style strings end at the first null character. so the line

printf("%c%c\0", '1', '0')

is equivalent to printf("%c%c", '1', '0') and the second null character in the original version (the one implicitly added by the compiler) is never looked at. Similarly, your other two working approaches output a '1' followed by a '0' and nothing else.

(The fourth version is a little different since the null character is in the last parameter instead of the first, but the principle is the same. That version is equivalent to printf("%c%c%s", '1', '0', "").)

The versions that fail force a null character to the output by presenting it as an independent character, rather than being part of a string.

What is the difference between printing "\0" and '\0'?

Printing "\0" is the same as printing "" since the null character ends the string (it's not part of the output). Printing '\0' will actually output the null character.

  •  Tags:  
  • c c
  • Related