Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

C/++/# Why can I print C-Strings without a Loop?

  1. Apr 11, 2017 #1
    Hey all,

    I have a question regarding C-Strings.

    Say I have the following function
    Code (C):

    #include <iostream>
    using namespace std;

    int main() {
       const int SIZE = 5;
       char cstr1[SIZE] = "Hi";
       cout << cstr1;
       return 0;
    This will actually print out the string literal.

    I'm confused because the book defines a C-String as: a sequence of characters stored in consecutive memory locations and terminated by a null character. And that a C-String can appear in a program as a programmer-defined arrays of character (like my above code).

    So I understand that "Hi" would have two subscripts 0 and 1, and at the end of the i it would have a null character \0. But, it'd also have two empty locations since I defined my array to carry 5 characters. However, since this is an array, shouldn't it require a loop? Does the compiler do this implicitly?

    Secondly, if a C-String stores the address of the first character of the string literal, why doesn't printing out cstr1 display an address?

    My book demonstrates these concepts but doesn't really explain why it's doing this.

  2. jcsd
  3. Apr 11, 2017 #2


    User Avatar

    Staff: Mentor

    Because the compiler "knows" that a C-string is supposed to be printed as a sequence of characters, not as an address.
  4. Apr 11, 2017 #3


    Staff: Mentor

    To expand on what @jtbell said, there are numerous overloaded versions of the << operator. If the object to be displayed (inserted into the output stream) is an int, char, long, bool, float, double, or other scalar type (i.e., not a pointer), the << operator causes that value to be displayed. If the object to be displayed is a string or the address of a character array, the << operator causes all characters in the string or char array to be displayed, stopping when it reaches the null character.
  5. Apr 11, 2017 #4
    No it doesn't. That behavior is defined in <iostream>.

    In C++ operators can be overloaded. One of the overloads for the << operation for this stream is for const char *. Because it's polymorphic, the compiler searches through the virtual functions of the same name until it finds one with the correct parameter signature, then it uses that. It's exactly the same as saying std::cout.append("Hi");
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook

Have something to add?
Draft saved Draft deleted