4

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).

JYelton
  • 32,302
  • 33
  • 134
  • 249
Decapod
  • 3,900
  • 9
  • 23

1 Answers1

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.

Justme
  • 127,425
  • 3
  • 97
  • 261
  • I agree with you.. But one has to discover first that it goes wrong. – Decapod Jul 20 '19 at 12:49
  • That's why C has the concept of [sequence points](https://en.wikipedia.org/wiki/Sequence_point), for when order is important. – Dave Tweed Jul 20 '19 at 13:23
  • @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 – Decapod Jul 21 '19 at 05:21
  • 1
    You already have a correct implementation -- your second implementation uses statement boundaries (";") as sequence points. – Dave Tweed Jul 21 '19 at 11:11