Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

What is the difference in "\n" AND '\n' #148

Open
mallikpramod opened this issue Aug 29, 2022 · 2 comments
Open

What is the difference in "\n" AND '\n' #148

mallikpramod opened this issue Aug 29, 2022 · 2 comments

Comments

@mallikpramod
Copy link

08-Considering_Performance.md
in the section Char is a char, string is a string (third from last)
How the performance in CPU different for "\n" and '\n' ?

@PercentBoat4164
Copy link

When the CPU is tasked with parsing "\n" it must perform a string length check. This means counting to the end of a one character array. On the other hand, when the CPU is tasked with parsing '\n' it is already done. That is just a single character of type char. There is no casting, length finding, or other tasks that need to happen. All of this comes from the key fact that the compiler treats any character in '' quotes as type char, and anything in "" quotes as type const char *. In fact it is illegal to use multiple characters inside of '' quotes in C/C++.

As already stated in the section:

This is very minor, but a "\n" has to be parsed by the compiler as a const char * which has to do a range check for \0 when writing it to the stream (or appending to a string). A '\n' is known to be a single character and avoids many CPU instructions.

The exact number of CPU instructions likely varies greatly with the compiler, but either way some are wasted, and therefore this is something to be considered while writing in C/C++.

@ViralTaco
Copy link

ViralTaco commented Oct 20, 2022

String literals in C++ (and C) are NULL terminated C-style 'arrays'.
"X" is equivalent to { 'X', '\0' }.
Therefore sizeof "\n" is 2. (sizeof (char) is always 1).

See:
cppreference.com: String Literal
9.4.3 Character arrays [dcl.init.string]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants