*ptr++
연산자 우선순위(Operator precedence)에 따라, 

후위 증감연산자 (post increment) ++가 역참조(deference) 연산자 * 보다 먼저 실행됨.

 

어? 만약 ptr이 배열 첫번째 원소를 가리키고 있었다면, *ptr++은 그럼 ++ 에 의해 ptr이 두번째 원소를 가리키게 되고,

*에 의해 두번째 원소를 반환하지 않나?

→ ㄴㄴ, 후위 증감연산자가 연산의 결과인 ptr+1을 반환하는게 아닌, 연산 전의 값인 ptr을 반환해서 첫번째 원소 반환

	int a[5] = {1,2,3,4,5};
	int* ptr = a;

	// Simple
	for(int i = 0; i < 5; i++)
	{
		printf("%d", *ptr);
		ptr +=1 ;
		// printf("%d", *ptr++); // can be put into single line 
	}

 

 

자매품 (구별할 줄 알아야 함)
(*ptr)++
++*ptr
*++ptr

 

 

 

Q. 후위 증감연산자는 언제 값을 바꾸는가? (When does post incre/decrement takes effect?)

후위 증감연산자의 작동 순서를 분석해보면 아래와 같다. 

연산을 실행하긴 하는데, 반환값이 연산 이전의 값.

int a = 0, b = 0;
int c = a++ + b++;

// Same as
int c = (a++) + (b++);

// Executed like..
auto __tmp1 = a;         // 1
auto __tmp2 = b;         // 2
++a;                     // 3
++b;                     // 4
int c = __tmp1 + __tmp2; // 5

*ptr++은, ++이 먼저 실행되긴 하나, 연산 결과인 ptr+1이 아닌 ptr을 반환하고 그게 역참조 되는 것.

 

stackoverflow.com/a/5434385

 

When does postincrement i++ get executed?

Possible Duplicate: Undefined Behavior and Sequence Points In C++ on a machine code level, when does the postincrement++ operator get executed? The precedence table indicates that postfix++

stackoverflow.com

 

+ Recent posts