C ++ weird std :: cout behavior using pointers

Possible duplicate:
What is the correct answer for cout <c ++ <c ;?

I just dropped the text when I suddenly noticed.

#include <iostream> int main() { int array[] = {1,2,3,4}; int *p = array; std::cout << *p << "___" << *(p++) << "\n"; // output is 1__1. Strange, but I used brackets! it should be at // first incremented, not clear. p = array; std::cout << *p << "___" << *(++p) << "\n"; // output is 2_2 fine, why first number was affected? I didn't intend // to increment it, but it was incremented p=array; std::cout << *p << "___" << *(p + 1) << "\n"; // output is 1_2 - as it was expected p = array; return 0; } 

Such behavior is strange to me, why is this so?

+4
source share
1 answer

You cause undefined behavior , so anything can happen, and there is no point in thinking about why.

Expression

 std::cout<<*p<<"___"<<*(p++)<<"\n" 

It is one example: the evaluation order of all things between << not specified, therefore *p and *(p++) not subject to sequence relative to each other (i.e. the compiler is not required to make the first one), you are not allowed to change the variable, and then use it without modification and use to be ordered , and therefore this leads to undefined behavior.

The same applies to all other places in the program where the variable is changed and used separately for one expression in one expression.

+15
source

Source: https://habr.com/ru/post/1436956/


All Articles