7

I learned the ASCII value of '\0' is 0, and the ASCII value of 0 is 0x30, but when I try to print their ASCII value using printf, I get the same output:

printf("\'\\0\' : %d\n", '\0');
printf("\'\\0\' in hex : %x\n", '\0');
printf("0 : %d\n", 0);
printf("0 in hex: %x\n", 0);

output:

'\0' : 0
'\0' in hex : 0
0 : 0
0 in hex: 0

why?

Victor S
  • 4,021
  • 15
  • 43
  • 54

7 Answers7

15

The ASCII character '0' is different than the number 0. You are printing the integer 0 in your second pair of printfs instead of '0'.

Try this:

printf("'\\0' : %d\n", '\0');
printf("'\\0' in hex : %x\n", '\0');
printf("'0' : %d\n", '0');
printf("'0' in hex: %x\n", '0');

Also, you don't need to escape ' inside strings. That is, "'" is fine and you don't need to write "\'"

Shahbaz
  • 46,337
  • 19
  • 116
  • 182
13

You confuse 0, '\0', and '0'.

The first two of these are the same thing; they just represent an int with value 0.

'0', however, is different, and represents an int with the value of the '0' character, which is 48.

houbysoft
  • 32,532
  • 24
  • 103
  • 156
3
printf("0 : %d\n", '0');

Print like this, you will get 48.

Prasad G
  • 6,702
  • 7
  • 42
  • 65
3

Yes, the character literal'\0' has value 0 and this is independent of the character set.

(K&R2, 2.3) "The character constant '\0' represents the character with value zero, the null character. '\0' is often written instead of 0 to emphasize the character nature of some expression, but the numeric value is just 0."

ouah
  • 142,963
  • 15
  • 272
  • 331
1

All of these answers seem to miss the point of \0 ...

Try this:

printf("This line\0 might not completely appear");

That's the reason for \0

So you can define a NULL terminated string ...

#define TEST_STRING "Test"

is quite different from

#define TEST_STRING "Test\0"

the latter being useful in certain cases.

Laurel
  • 5,965
  • 14
  • 31
  • 57
Dr Jeff
  • 11
  • 1
  • 2
    `"Test"` is a null-terminated string. – M.M Jun 02 '16 at 22:30
  • You are correct - senility must be setting in ... #define NAME_DESC "Dog\0A four legged friend" would have been a better example, using the '\0' to 'hide' the description from standard functions and catenate a second string (the description). I merely meant to show it has a usefulness. – Dr Jeff Jun 04 '16 at 12:33
0

The ASCII value for '\0' is indeed 0. But '\0' is different from '0' (notice the backslash, which is the escape symbol).

sashoalm
  • 75,001
  • 122
  • 434
  • 781
0

Your last line should be

printf("0 in hex: %x\n", '0');
Wernsey
  • 5,411
  • 22
  • 38