Reputation: 25
#include <iostream>
using namespace std;
int main()
{
char str[] {"TESTING"};
char *p {str};
cout << (p++, *++p);
cout << *p++;
cout << p;
return 0;
}
It returns "SSTING"
I know maybe this post isn't exactly for stackoverflow but I can't figure out what it does, and couldn't find any documentation about it
cout << (p++, *++p);
First time I saw round brackets with comma in cout... what's their function?
and shouldn't this line alone say "TESTING" but it seems to say only TING
cout << p;
Thank you!
Upvotes: 0
Views: 67
Reputation: 2767
Not exactly an answer, but a breakdown of what was the code doing,
#include <iostream>
using namespace std;
int main()
{
char str[]{"TESTING"};
char *p{str}; // p points to: 'T'
p++; // p points to: 'E'
++p; // p points to: 'S'
cout << *p; // output a single char: 'S'
cout << *p; // ouptut a single char: 'S'
p++; // p points to: 'T'
cout << p; // output a (char *) type pointer, AKA a C-string, "TING";
return 0;
}
Upvotes: 1
Reputation: 98348
Let's go line by line:
char str[] {"TESTING"};
This line defines a variable named str
of type array of 8 chars, and initializes it with the characters TESTING
plus a NUL char to mark the end.
char *p {str};
This one defines a variable named p
of type pointer to char and initializes it to the address of the first char of the array str
(the first T
). This happens because the array automatically decays into a pointer in most uses.
cout << (p++, *++p);
This line does several things. The ,
operator first evaluates the left-hand operator p++
, that increments the pointer, now points to the E
; then it evaluates the right-hand operator *++p
, but that is a pre-increment operator so it increments the pointer again (it points to S
). Finally the *
operator accesses to the memory pointed to by p
, the result is a S
. And that character is printed into STDOUT.
cout << *p++;
This one is easy. The *
operator accesses the char pointed to by p
(the S
again) and prints it in STDOUT. Then it increments the pointer, because it is a post-increment operator. Now it points to the second T
.
cout << p;
And at least, this line prints the string pointed to by p
until it finds a NUL character. Since p
is pointing to the second T
of your array it will print TING
.
Putting all those outputs together you get SSTING
.
Upvotes: 2