-
August 3rd, 2010, 08:14 AM
#10
Re: A question regarding *s++
Originally Posted by monarch_dodra
Maybe you are confusing evaluation order?
Regardless of type, when you write:
Both p++ and q++ are evaluated first (but in undefined relative order).
Once this is done, operator= is called on the return values of p++ and q++, ie, the old values of p and q. (making it look like the assignment took place before increment)
There is no special magic or rules that applies only to PODs that do the assignments first, and then increments the values of p or q.
...
Either that, or I seem to not understand what you are saying. Your example (rewritten since incomplete) seems to work correctly:
Code:
#include <iostream>
#include <string>
int main()
{
char pArray[20] = { '\0' };
char* p = pArray;
std::string helloStr = "Hello";
//force the null terminator into string //Undefined behavior, but defined in practice
helloStr.c_str();
std::string::iterator q = helloStr.begin();
while (*p++ = *q++); //note that this reads string.end(), but should point '\0'. May crash in ranged debug
std::cout << pArray << std::endl;
}
Was this your full example?
Regards,
No, it was from my memories ;-)
Here is the code that compiles:
Code:
#include <iostream>
int main()
{
char * q = "Hello";
char buf[20] = { '\0' };
char * p = buf;
while (*p++ = *q++);
std::cout << buf << std::endl;
return 0;
}
If incrementation would happen before assignment the p[0] would not be set correctly.
I will add the string class example soonly.
Regards, Alex
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|