cpp-best-practices / cppbestpractices

Collaborative Collection of C++ Best Practices. This online resource is part of Jason Turner's collection of C++ Best Practices resources. See README.md for more information.
Other
8.02k stars 877 forks source link

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

Open mallikpramod opened 2 years ago

mallikpramod commented 2 years ago

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 commented 2 years ago

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 commented 1 year ago

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]