후위 연산에 대해

익명 사용자의 이미지

저는
1
1
로 출력될 것으로 예상하고 했는데
2
1
로 출력이 됬는데 이유를 모르겠더라구요

i++ 식으로되면 원래 i 값으로 cout하고 그 다음 증가하는 것으로 알고 있는데
오히려 처음 a[i]가 증가된 값으로 나오는 이유를 모르겠습니다..

File attachments: 
첨부파일 크기
Image icon 후위연산.PNG6.22 KB
tt..의 이미지

 int a[5] = { 0,1,2,3,4 };
 int i = 1;
 cout << a[i] << endl << a[i++] << endl;

cout << a[i] << endl << a[i++] << endl;
에서 a[i++] 먼저 수행. 이때 i 는 1
그 후 a[i] 수행. 이때 i 는 2

작성자의 이미지

저는 당연하게 a[i]가 먼저 수행된다고 생각했는데
a[i++]이 먼저 수행되는 이유가 따로 있을까요

tt..의 이미지

https://en.cppreference.com/w/c/language/eval_order

아래부분을 보시면

Undefined behavior
1) If a side effect on a scalar object is unsequenced relative to another side effect on the same scalar object, the behavior is undefined.

i = ++i + i++; // undefined behavior
i = i++ + 1; // undefined behavior
f(++i, ++i); // undefined behavior
f(i = -1, i = -1); // undefined behavior

2) If a side effect on a scalar object is unsequenced relative to a value computation using the value of the same scalar object, the behavior is undefined.

f(i, i++); // undefined behavior
a[i] = i++; // undefined bevahior

이라고 나와있습니다.

raymundo의 이미지

mac에 있는 gcc(LLVM 기반?)으로 컴파일하면 1 1이 나옵니다만, 여지없이 컴파일할 때 경고가 뜨는군요.

$ g++ t.cpp
t.cpp:10:32: warning: unsequenced modification and access to 'i' [-Wunsequenced]
    cout << a[i] << endl << a[i++] << endl;
              ~                ^
1 warning generated.

제가 아는 한,
한 statement 안에서 한 변수의 값을 변경시키는(i++)코드와 값을 읽는 코드([i])가 섞여 있으면 그 동작순서나 결과는 C와 C++에서는 정의되지 않았습니다. 그러니 아예 쓰지 않는 것이 답입니다.

좋은 하루 되세요!