Why can I print C-Strings without a Loop?

  • C/++/#
  • Thread starter MinusTheBear
  • Start date
  • #1

Main Question or Discussion Point

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";
   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.

Thanks.
 

Answers and Replies

  • #2
jtbell
Mentor
15,580
3,559
Does the compiler do this implicitly?
Yes.
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.
 
  • #3
33,719
5,417
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.
 
  • #4
1,516
617
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::cout.append("Hi");
 

Related Threads on Why can I print C-Strings without a Loop?

Replies
1
Views
11K
  • Last Post
2
Replies
26
Views
4K
Replies
8
Views
605
Replies
18
Views
6K
Replies
9
Views
1K
  • Last Post
Replies
4
Views
2K
Replies
4
Views
364
  • Last Post
Replies
3
Views
1K
  • Last Post
Replies
1
Views
1K
Top