tags:

views:

301

answers:

5

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?

+21  A: 

'\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.

mikerobi
+1  A: 

Single quotes denote a character and double quotes denote a string. Depending on the context, you can choose which data type to work with.

Hollister
+2  A: 

'\n' is a char constant.

"\n" is a const char[2].

So usage is something like this:

char newLine = '\n';
const char* charPointerStringNewLine = "\n"; // implicit conversion
const char[2] charStringNewLine = "\n";

string stringNewLine( "\n" );

So in short: one is a pointer to a character array, the other is a single character.

rubenvb
`"\n"` is a `const char[2]`, not a `const char*`. The former is implicitly convertible to the latter, though.
GMan
@GMan: fixed it. Thanks
rubenvb
+8  A: 

'\n' is a char literal. "\n" is a string literal (an array of chars, basically).

The difference doesn't matter if you're writing it to an ordinary stream. std::cout << "\n"; has the same effect as std::cout << '\n';.

In almost every other context, the difference matters. A char is not in general interchangeable with an array of chars or with a string.

So for example std::string has a constructor which takes a const char*, but it doesn't have a constructor which takes a char. You can write std::string("\n");, but std::string('\n'); doesn't compile.

std::string also has a constructor which takes a char and the number of times to duplicate it. It doesn't have one that takes a const char* and the number of times to duplicate it. So you can write std::string(5,'\n') and get a string consisting of 5 newline characters in a row. You can't write std::string(5, "\n");.

Any function or operation that you use will tell you whether it's defined for a char, for a C-style string, for both via overloading, or for neither.

Steve Jessop
typo! Forgot the slash in the second case: `std::cout << '\n';`.
leo grrr
@leo grrr: thanks, but beat you to it :-)
Steve Jessop
A: 

I understand the '\n' represents a char and "/n" represents a string but does this matter?

If you understand this, then it should be clear that it does indeed matter. Overloaded functions in the C++ standard library often hide this fact, so maybe an example from C will be more useful: putchar takes a single character, so only '\n' is correct, whereas puts and printf take a string, and in that case, only "\n" is correct.

casablanca