Pointer incrementing C

Consider the following code:

unsigned short i;
unsigned short a;
unsigned char *pInput = (unsigned char *)&i;

pInput[0] = 0xDE;
pInput[1] = 0x01;

a = ((unsigned short)(*pInput++)) << 8 | ((unsigned short)(*pInput++));

Why is the value of a equal to 0xDEDE and not 0xDE01?

+4
source share
3 answers

The code invokes undefined behavior . The reason is that it pInputis modified more than once between two points in a sequence . You can get anything, the expected or unexpected result. Nothing can be said.

C99 claims that:

, . , , .

c-faq 3.8.

+5

pInput, undefined.

:

a = ((unsigned short)(*pInput++)) << 8;
a |= ((unsigned short)(*pInput++));
+1
a = ((unsigned short)(*pInput++)) << 8 | ((unsigned short)(*pInput++));

post increment, ++ .

a , :

a = ((unsigned short)(*pInput)) << 8 | ((unsigned short)(*pInput));

, 0xDE01, :

a = ((unsigned short)(*pInput)) << 8 | ((unsigned short)(*(pInput+1)));
0

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


All Articles