Why can I print C-Strings without a Loop?

  • Context:
  • Thread starter Thread starter MinusTheBear
  • Start date Start date
  • Tags Tags
    Loop
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
3 replies · 2K views
MinusTheBear
Messages
22
Reaction score
0
Hey all,

I have a question regarding C-Strings.

Say I have the following function
C:
#include <iostream>
using namespace std;

int main() {
   const int SIZE = 5;
   char cstr1[SIZE] = "Hi";
   count << 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.

Thanks.
 
Physics news on Phys.org
MinusTheBear said:
Does the compiler do this implicitly?
Yes.
MinusTheBear said:
if a C-String stores the address of the first character of the string literal, why doesn't printing out cstr1 display an address?
Because the compiler "knows" that a C-string is supposed to be printed as a sequence of characters, not as an address.
 
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.
 
jtbell said:
Because the compiler "knows" that a C-string is supposed to be printed as a sequence of characters, not as an address.
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::count.append("Hi");