Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String termination - char c=0 vs char c='\0'

When terminating a string, it seems to me that logically char c=0 is equivalent to char c='\0', since the "null" (ASCII 0) byte is 0, but usually people tend to do '\0' instead. Is this purely out of preference or should it be a better "practice"?

What is the preferred choice?


EDIT: K&R says: "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.

like image 417
Joe DF Avatar asked Jun 06 '13 07:06

Joe DF


People also ask

What is the terminating character of a string in C?

Strings are actually one-dimensional array of characters terminated by a null character '\0'.

What is the purpose of '\ 0 character in C?

\0 is zero character. In C it is mostly used to indicate the termination of a character string. Of course it is a regular character and may be used as such but this is rarely the case. The simpler versions of the built-in string manipulation functions in C require that your string is null-terminated(or ends with \0 ).

Why we use '\ 0 at the end of the string?

it is used to show that the string is completed.it marks the end of the string. it is mainly used in string type.by default string contain '\0\ character means it show the end of the character in string. end of the array contain ''\0' to stop the array memory allocation for string name.

Which is the string termination character?

All character strings are terminated with a null character. The null character indicates the end of the string. Such strings are called null-terminated strings.


Video Answer


1 Answers

http://en.wikipedia.org/wiki/Ascii#ASCII_control_code_chart

Binary   Oct  Dec    Hex    Abbr    Unicode  Control char  C Escape code   Name 0000000  000  0      00     NUL     ␀       ^@            \0              Null character 

There's no difference, but the more idiomatic one is '\0'.

Putting it down as char c = 0; could mean that you intend to use it as a number (e.g. a counter). '\0' is unambiguous.

like image 116
Nobilis Avatar answered Oct 11 '22 00:10

Nobilis