What is the difference between "\n" and '\n'.?
Also what is the difference between " " and ' '??

Dani AI

Generated

gave the correct short answer. A few practical details that often cause confusion follow.

In C++ a single-quoted character literal has type char; in C it is an int (so sizeof('x') can differ between the two languages). A string literal has array type (in C++ it is const char[N]) and decays to a pointer to its first element in most expressions. That means sizeof applied to a character variable and to a small string literal produce different results:

char ch = 'A';
const char s[] = "A";

sizeof(ch)   // typically 1
sizeof(s)    // typically 2 (character plus terminator)

Function dispatch and assignment behave differently too. Overloads or APIs that expect a char will accept a character literal; those that expect a C string will take a pointer/array. Do not assign a string literal to a non-const char* in modern C++ — use const char* or std::string instead:

void f(char);
void f(const char*);

f('A');   // calls f(char)
f("A");   // calls f(const char*)

Extra cautions: multi-character character literals (more than one char inside single quotes) are implementation-defined and should be avoided. Attempting to modify the contents of a string literal is undefined behavior. For most code, prefer std::string for safety and clarity when you need a textual sequence; use single quotes only for single-character values.

Recommended Answers

All 2 Replies

>What is the difference between "\n" and '\n'.?
>Also what is the difference between " " and ' '??
Nothing. :D

But seriously, the first is a string literal and the second is a character literal. The difference, aside from the data type, is that a string literal is an array of const char that always has a '\0' character at the end and a character literal isn't an array and doesn't have a null character.

Thank you Narue!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.