I just wrote the following line of code:
if (++(data_ptr->count) > threshold) { /*...*/ } // example 1
My intent is to increment the count
variable within the data structure that data_ptr
points to before making the comparison to threshold
, and this line of code works.
If I had instead wanted to increment data_ptr
before making the comparison, I would have written this:
if ((++data_ptr)->count > threshold) { /*...*/ } // example 2
Out of curiosity, I also tried this line of code:
if (++data_ptr->count > threshold) { /*...*/ } // example 3
And found that it behaves exactly the same as the first one.
First question: Why does example #3 work the same as example #1? Is it a matter of operator precendence? Something in the standard? I had to write a quick test program becuase the answer was not obvious to me.
Second question: Should I write this if
statement differently? I could perform the increment first, on its own line, and then test the condition in order to avoid any possible confusion. Is this necessary, or are the first two examples obvious enough on their own?