0

I am trying to find out, why the output of the following program is "WAHNAHNN".

My question is: Why does the index i rise above p[4] (i.e. exceed the length of the array) and why does it produce another "AHNN" after the "WAHN"?

I am still confused with the difference between p+i (which should be a location) and *(p+i) which should be a value. Why is the output a value in both cases?

 #include <iostream>
 using namespace std;
 int main()
 {
     char a[] = "WAHN";
     char *p = a;
     for (int i=0; p[i]; i=i+1)
         switch (i%2) {
             case 0: cout << p+i;
             break;
             case 1: cout << *(p+i);
             break;
         }
     return 0;
}
3
  • The reason is that the operator << on ostream is overloaded for char * as you can see in the documentation Commented Oct 31, 2014 at 12:38
  • It is difficult to understand what is your confusion. i=0 print the string "WAHN", i=1 print the character "A", i=2 print the string "HN", i=3 print the character "N", then it's what's you code. Commented Oct 31, 2014 at 12:40
  • 1
    @mpromonet Please do not add C tags to questions that contain C++ code. Commented Oct 31, 2014 at 15:01

1 Answer 1

4

The type of p + i is char*.

The operator << interprets this as a nullterminated string. This means that the program will output "WHAN" (i == 0 so p + i == p, wich is the same as a) for the first iteration, "A" for the second iteration, "HN" for the third and "N" for the last one.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.