View previous topic :: View next topic |
Author |
Message |
canadidan
Joined: 13 Feb 2019 Posts: 24
|
[PIC24HJ256GP210] Increment operator issue with int32 array |
Posted: Wed Jun 19, 2019 7:11 am |
|
|
Before I get started, this post is mostly to have a record on the internet for others with similar issues since I couldn't find anything else like it.
PIC-C Version 4.106 (very old)
Problem
I have an array of 32 bit signed integers:
Code: | signed int32 Count[6]; |
I have a loop that gets called over 100k times, and increments a particular element in the array like so:
The number of times the loop is called is variable (based on user input/configuration).
When the loop was called more than a certain amount of times, the count would be wrong. It was very easy to see what happened:
0x0001FFFF -> 0x00010000
It failed to increment the most significant 2 bytes.
Workaround
There is an easy way to deal with this:
Code: | Count[ID] = Count[ID] + 1; |
For some reason, this properly increments the Count element, unlike the ++ operator.
Why?
Has anyone seen this before, and can they tell me what's going on?
* Issue with compiler?
* Silicon Errata?
* My understanding of C for the last 10 years is fundamentally flawed?
Thanks! |
|
|
dluu13
Joined: 28 Sep 2018 Posts: 395 Location: Toronto, ON
|
|
Posted: Wed Jun 19, 2019 7:45 am |
|
|
I have no idea about the questions you posted at the end, but I am curious: What if you use ++Count[ID] instead of Count[ID]++?
What about Count[ID] += 1?
As I understand it post incrementing, it needs to save the current value before incrementing the value, and then it returns the current value. In contrast, preincrementing just increments the value and returns the incremented value. There's less steps there...
So there might be something to do with that? |
|
|
Ttelmah
Joined: 11 Mar 2010 Posts: 19549
|
|
Posted: Wed Jun 19, 2019 8:55 am |
|
|
It is specific to the low 4.1xx compilers.
Just wrote a basic test. Works find if the array index is fixed.
Fails on int32 or unsigned int32, at the wrap from 0x1FFFF to 0x20000.
In 4.141, it happily works OK.
sum[ID]+=1l
works OK. |
|
|
canadidan
Joined: 13 Feb 2019 Posts: 24
|
|
Posted: Wed Jun 19, 2019 9:18 am |
|
|
@dluu13 - great points. The +=1 notation more clearly shows intended behaviour, so I used that and it works correctly.
Code: | Count[ID] += 1; // This works |
@Ttelmah - I had a feeling you would know what was going on. Thanks for clarifying the history through compiler versions.
Hopefully this can help someone else! |
|
|
|