0

I've been using C and C++ since quite a while, and I just happened to come across a program that had single quotes for \n like it was a character ( '\n' ) . It serves the purpose alright, and my assumption is something on the lines of a string consisting of an array of characters and \n is a single character and hence doesn't make any difference. My 2 questions are:

  1. Why isn't this methodology popular?
  2. Is \n actually a single character as I'm assuming it to be?
GeeYes
  • 88
  • 6
  • @ChrisCulter, not really. OP knows chars and string, but apparently not escape sequences. (The question probably is a duplicate, though, just not for the question that you linked.) – Kijewski Nov 06 '14 at 07:08
  • @Yu Hao No, I was referring to us mostly using "\n " and not '\n'. – GeeYes Nov 06 '14 at 07:16
  • 3
    The difference between `"\n"` and `'\n'` is the same as the difference between `"a"` and `'a'`. You use the one you need, a string literal or a single `char`. – Yu Hao Nov 06 '14 at 07:17

3 Answers3

1

See "Escape sequences". '\n' ubiquitously means newline. In ASCII this is code 10 (0x0A). All C derived languages (C++, Java, JavaScript, but also e.g. Prolog, Bash, Python, …) use '\n' as escape sequence for the newline character.

Kijewski
  • 25,517
  • 12
  • 101
  • 143
1

They are single characters, called control characters. We need to be able to see and type them so they are written as a combination of visible characters available on keyboards.

ryanpattison
  • 6,151
  • 1
  • 21
  • 28
1

The key difference between "\n" and '\n' is that "\n" is a string with a newline character (i.e. a buffer consisting on two bytes: 0x0A and 0x00, being 0x00 the standard end of line indicator in C strings) whereas '\n' is just the constant 0x0A.

Claudi
  • 5,224
  • 17
  • 30
  • 1
    "whereas '\n' is just the constant 0x0A": this part is not entirely correct. C does not mandate the encoding. E.g. in EBCDIC the code for a newline is different. – Kijewski Nov 06 '14 at 07:21