I've seen the new line \n
used 2 different ways in a few code examples I've been looking at. The first one being '\n'
and the second being "\n"
. What is the difference and why would you use the '\n'
?
I understand the '\n'
represents a char and "\n"
represents a string but does this matter?
\0 is the null byte, used to terminate strings. \n is the newline character, 10 in ASCII, used (on Unix) to separate lines.
The newline character ( \n ) is called an escape sequence, and it forces the cursor to change its position to the beginning of the next line on the screen. This results in a new line.
in Unix and all Unix-like systems, \n is the code for end-of-line, \r means nothing special. as a consequence, in C and most languages that somehow copy it (even remotely), \n is the standard escape sequence for end of line (translated to/from OS-specific sequences as needed)
CR = Carriage Return ( \r , 0x0D in hexadecimal, 13 in decimal) — moves the cursor to the beginning of the line without advancing to the next line. LF = Line Feed ( \n , 0x0A in hexadecimal, 10 in decimal) — moves the cursor down to the next line without returning to the beginning of the line.
'\n'
is a character constant.
"\n"
is a pointer to character array equivalent to {'\n', '\0'}
(\n
plus the null terminator)
EDIT
I realize i explained the difference, but didn't answer the question.
Which one you use depends on the context. You use '\n'
if you are calling a function that expects a character, and "\n"
, if it expects a string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With