what is the correct string terminator in c

41,826

Solution 1

The only value that can be used as a null terminator is the numerical value 0.

  • 0 is the numerical value 0.
  • '\0' is also another way of representing the numerical value 0 in your code
  • '0' is not the numerical value 0 (it's the digit zero) and cannot be used as a terminator.

All strings literals implicitly contain the null terminator after their last visible character. In other cases, it may or may not be there automatically (depending on how the string was constructed), but you have to be sure that in every case the null terminator is there.

Solution 2

  • is the null character equal to the literal 0?

Yes.

The null character (also null terminator), abbreviated NUL, is a control character with the value zero.

  • can we use '0' as the terminating character too?

No. '0' is a character which has value 0x30. It is not null character and not equal to 0.

See this link: http://www.asciitable.com/

Solution 3

'\0' is a convenient way of entering byte 0. It's called escaping. '0' is the character zero; very different. All strings in c are terminated with byte 0.

Solution 4

In C, strings are arrays of char's terminated with a '\0'. When writing a char with single quotes, as in '\0' you are reffering to the asci value of that char. Thus the expression: return '\0' == 0; would return true.

Share:
41,826
DesirePRG
Author by

DesirePRG

Updated on July 24, 2022

Comments

  • DesirePRG
    DesirePRG almost 2 years

    As I know the string terminating character in c is '\0'.

    can we use '0' as the terminating character too? when I assign 0 to a specific index in a char array, and then use printf, it prints only upto that specific index.

    hence, are both ways equivalent? is the null character equal to the literal 0?