To save time and reading I copied a code block from a program found on the internet to determine the X angle of inclination.

int Ay = (((int)I2C_Read(0)<<8) | (int)I2C_Read(0));
int Az = (((int)I2C_Read(0)<<8) | (int)I2C_Read(1));

During the executing I could not get the expected results. Comparing the code with a similar code block in an Arduino sketch showed a good approach. The Arduino sketch worked well but the pic program behaved strange. Finally I decided to hook up a logic analyzer and noticed the incoming byte before last had the NACK instead of the last one. I decided to change the code into:

AcY = (int)I2C_Read(0)<<8;
AcY +=(int)I2C_Read(0);
AcZ = (int)I2C_Read(0)<<8; 
AcZ +=(int)I2C_Read(1);

Now the results are correct. This brings me to the conclusion that the executing order is different depending on the environment. It would be nice to know if my conclusion is correct and is it possible to change the behavior of the compiler (XC8).


1 Answer 1


Order of evaluation is not defined by standard. It is up to the compiler how it implements this. Refer to the compiler manual if it can be changed. I highly doubt it is changeable. Besides, it would be just easier to write code that does not require certain assumptions about the compiler or its configuration.

  • \$\begingroup\$ I agree with you.. But one has to discover first that it goes wrong. \$\endgroup\$
    – Decapod
    Jul 20, 2019 at 12:49
  • \$\begingroup\$ That's why C has the concept of sequence points, for when order is important. \$\endgroup\$
    – Dave Tweed
    Jul 20, 2019 at 13:23
  • \$\begingroup\$ @DaveTweed. I try to understand the remarks in Wikipedia but it remains unclear to me how to implement this in the given example. Could you create an answer showing the implementation \$\endgroup\$
    – Decapod
    Jul 21, 2019 at 5:21
  • 1
    \$\begingroup\$ You already have a correct implementation -- your second implementation uses statement boundaries (";") as sequence points. \$\endgroup\$
    – Dave Tweed
    Jul 21, 2019 at 11:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.