2012-09-29 5 views
4

가능한 중복 : 나는 갑자기 발견
What is the correct answer for cout << c++ << c;?C++ 이상한 표준 : : cout과 동작을 사용하여 포인터

나는 단지 ouputted 텍스트.

#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; 
} 

이러한 동작은 저에게 이상합니다. 그 이유는 무엇입니까?

+2

동일한 표현식에서 인수를 사용하여 증가분을 사용하면 정의되지 않은 동작이 호출됩니다. – Joe

+2

[정의되지 않은 동작 및 시퀀스 포인트] (http://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points)를 참조하십시오. –

답변

15

당신은 undefined behaviour을 유발하고 있습니다. 따라서 아무 일도 일어나지 않을 수 있으며 이유에 대해 추측 할 필요가 없습니다.

표현

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

한 예입니다 << 사이의 모든 것들의 평가 순서가 지정되어 있지 않은, 그래서 *p*(p++) (즉, 컴파일러가해야합니까 필요하지 않습니다 서로에 대해 unsequenced된다 둘 중 하나 먼저). You are not allowed to modify a variable and then use it without the modification and usage being sequenced 및 이로 인해 정의되지 않은 동작이 발생합니다.

같은 것을 변수가 수정되어 동일한 식에서 별도로 시퀀싱되지 않은 상태로 사용되는 해당 프로그램의 다른 모든 위치에 적용됩니다.

관련 문제